Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.

  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint
Share this Page URL

Chapter 9. More Library Puzzlers > Puzzle 77: The Lock Mess Monster

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)
        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;
    // Rescind quitting time - Called by evil boss
    synchronized void keepWorking() {
        quittingTime = false;

    public static void main(String[] args)
            throws InterruptedException {
        final Worker worker = new Worker();

        Timer t = new Timer(true); // Daemon thread
        t.schedule(new TimerTask() {
            public void run() { worker.keepWorking(); }
        }, 500);




You are currently reading a PREVIEW of this book.


Get instant access to over $1 million worth of books and videos.


Start a Free 10-Day Trial

  • Safari Books Online
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint