简体   繁体   中英

Thread not giving correct output

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

You're accessing the two.variable1 from multiple threads without any kind of synchronization. So you have a visibility problem: the second thread reads the value of the variable from its internal cache, and is not aware that it has been changed by the first thread.

You should make the variable volatile , or use an AtomicBoolean , or access it using a synchronized method, to ensure that the write to the variable is flushed to the main memory and the variable is read from the main memory.

The call to System.out.println() has the side effect of making the variable visible because the println method is synchronized.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM