Java Reference
In-Depth Information
< Day Day Up >
Puzzle 77: The Lock Mess Monster
This program runs a little workplace simulation. It starts a worker thread that works— or at least
pretends to work— until quitting time. Then the program schedules a timer task representing an evil
boss who tries to make sure that it's never quitting time. Finally, the main thread, representing a
good boss, tells the worker when it's quitting time and waits for the worker to finish. What does the
program print?
import java.util.*;
public class Worker extends Thread {
private volatile boolean quittingTime = false;
public void run() {
while (!quittingTime)
pretendToWork();
System.out.println("Beer is good");
}
private void pretendToWork() {
try {
Thread.sleep(300); // Sleeping on the job?
} catch (InterruptedException ex) { }
}
// It's quitting time, wait for worker - Called by good boss
synchronized void quit() throws InterruptedException {
quittingTime = true;
join();
}
// Rescind quitting time - Called by evil boss
synchronized void keepWorking() {
 
 
Search WWH ::




Custom Search