0

I got two threads running on Main.java and a boolean field Main.bool which is false in the beginning. The first thread will set Main.bool to true. After that, The second thread will print out Main.bool. And the result is FALSE.

More interesting, I tried to print out a random text before printing Main.bool, then the result turned out to be correct(true).

Anyone have an idea what is going on here? I'm using eclipse Kepler.

Main.bool = false;
thread1.setBool(true);
// then wait for some seconds
// case 1
thread2.printBool(); --> false
// case 2
System.out.println("blah blah");
thread2.printBool(); --> true
Aliencc
  • 89
  • 1
  • 1
  • 6

1 Answers1

0

Make your filed 'bool' as volatile.

Any write to a volatile variable establishes a happens-before relationship with subsequent reads of that same variable

For more info.

Note: Making a field volatile, ensures that anyone who is reading the value of that field reads it from the memory and not from the local copy.

Aditya
  • 1,334
  • 1
  • 12
  • 23
  • yes thank you, I do know about volatile field, I just don't understand why it happened that way, and yours seems to be the right answer:) – Aliencc Mar 05 '14 at 07:08