a little program using threads is really bugging me, could anybody explain why this is not giving the output I think it should be?
class FirstClass {
public static void main(String args[]) {
Class2 two = new Class2();
Thread thread1 = new Thread(two);
thread1.start();
Class3 three =new Class3(two);
Thread thread2 = new Thread(three);
thread2.start();
}
}
class Class2 implements Runnable {
public Boolean variable1 = false;
@Override
public void run() {
System.out.println("Sleeping thread");
try {
Thread.sleep(3000);
}catch(Exception e){}
variable1=true;
System.out.println("Variable 1 = " + variable1);
}
}
class Class3 implements Runnable {
Class2 two;
public Class3(Class2 _two) {
this.two = _two;
}
@Override
public void run() {
while(!this.two.variable1) {
//System.out.println("in while");
}
System.out.println("Variable1 was changed to true");
}
}
The above, will give me the correct output, which is 'sleeping thread', 'variable1 = true', 'variable1 was changed to true'. Now if I change the program slightly and uncomment the 'System.out.println("in while");' I do not get the "Variable1 was changed to true', it is like it is not breaking out of the while loop, but why would 'System.out.println("in while")' make it break out? Or maybe it isn't? If anyone could explain what is happening I would be most grateful.
Thanks