Java Reference
In-Depth Information
quittingTime = false;
}
public static void main(String[] args)
throws InterruptedException {
final Worker worker = new Worker();
worker.start();
Timer t = new Timer(true); // Daemon thread
t.schedule(new TimerTask() {
public void run() { worker.keepWorking(); }
}, 500);
Thread.sleep(400);
worker.quit();
}
}
Solution 77: The Lock Mess Monster
The best way to figure out what this program does is to simulate its execution by hand. Here's an
approximate time line; the times are relative to the time the program starts running:
300 ms: The worker thread checks the volatile quittingTime field to see whether it's quitting
time; it isn't, so the thread goes back to "work."
400 ms: The main thread, representing the good boss, invokes the quit method on the worker
thread. The main thread acquires the lock on the worker THRead instance (because quit is a
synchronized method), sets quittingTime to TRue , and invokes join on the worker thread.
The join invocation does not return immediately but waits for the worker thread to complete.
500 ms: The timer task, representing the evil boss, executes. It tries to invoke the
 
 
Search WWH ::




Custom Search