I am reading Effective Java and in Chapter 10: Concurrency; Item 66: Synchronize access to shared mutable data, there is some code like this:
public class StopThread {
private static boolean stopRequested;
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
System.out.println(stopRequested);
Thread backgroundThread = new Thread(new Runnable(){
@Override
public void run() {
// TODO Auto-generated method stub
int i = 0;
while (!stopRequested){
i++;
}
System.out.println("done");
}
});
backgroundThread.start();
TimeUnit.SECONDS.sleep(1);
stopRequested = true;
}
}
First, I think the thread should run one second and then stop, since the stopRequested is set to true afterwards. However, the program never stops. It will never print done. The author said
while (!stopRequested)
i++;
will be transformed into this:
if (!stopRequested)
while(true)
i++;
Could someone explain me this?
And another thing I find is that if I change the program to this:
public class StopThread {
private static boolean stopRequested;
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
System.out.println(stopRequested);
Thread backgroundThread = new Thread(new Runnable(){
@Override
public void run() {
// TODO Auto-generated method stub
int i = 0;
while (!stopRequested){
i++;
System.out.println(i);
}
System.out.println("done");
}
});
backgroundThread.start();
TimeUnit.SECONDS.sleep(1);
stopRequested = true;
}
}
The program runs 1 second and stops as expected. What's the difference here?
