I tried the following and it didn’t work:
“Start” class:
public class Start implements Runnable {
Start start;
LoadExample loadExample;
Thread mainThread;
Thread loadExampleThread;
private boolean running = false;
public static boolean isExampleLoaded = false;
public static void main(String[] args) {
begin = new Start();
loadExample = new LoadExample();
begin.start();
}
public synchronized void start() {
mainThread = new Thread(this, "Main");
mainThread.start();
loadExampleThread = new Thread(loadExample, "Load Example");
loadExampleThread.start();
}
public void run() {
running = true;
while (running) {
if(isExampleLoaded){
System.out.println("Loaded!");
}
}
}
}
“LoadExample” class:
public class LoadExample implements Runnable {
public void run(){
//blabla, loading if you will...
Start.isExampleLoaded = true;
}
}
You might find syntax errors in the code above but that is only because I typed this without checking in Eclipse. My original code was very similar and Eclipse showed no errors or warnings.
My problem is that the code won’t print “Loaded!”.
I think this is either because (1) thread’s can’t change static variables or variables of other classes, or (2) the change is only update for the current thread and not for the other(s), but I may be wrong.
Any clarification is appreciated.
EDIT:
If you find any errors above, let me know and I will update them ASAP.
You need to mark the variable
volatilein order for this example to work. Withoutvolatile, the reading thread will readisExampleLoadedonce, and not read it again, because the compiler knows that the variable has not been written to.