If another thread calls end (), will Foo immediately see that false is now active?
No, it will not. Or at least he won’t see all this time.
If you want run always display the new value immediately, there must be a "come after" relationship between the thread assigned to the variable and the thread reading it. This can be achieved:
- declaring
active volatile, - by putting
synchronized blocks around statements that read and write a variable, - making the variable an "atomic" type; e.g.
AtomicBoolean , or - using another suitable concurrency class; see
java.util.concurrent.* packages.
... a smart way to avoid volatiles ...
Declaring a variable to be volatile is one way to ensure proper synchronization. It is a fact that proper synchronization incurs overhead. However, proper synchronization is necessary for the reliable operation of your application, and is NOT smart to avoid it.
(Without proper synchronization, your program will probably work most of the time, and it may even work on some machines. However, sometimes this will not work, and the actual behavior will probably depend on which machine you run the program on, which load cars, etc.)
Also, if another thread calls hibernate (), which thread will sleep?
The thread causing the call will go into sleep mode. And it will not wake up if some other thread does not execute notify or notifyAll on the same Foo object.
If you just want the application to Thread.sleep bit, use Thread.sleep . But be careful that using sleep wrong way can make your application slow and unresponsive.
Stephen C Aug 27 '11 at 2:35 a.m. 2011-08-27 02:35
source share