`

about Thread.join method

阅读更多
import java.util.Timer;
import java.util.TimerTask;

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() {

		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();

	}

}

 

If you run the above code, the program just hangs repeatably. why? anwser is located in Java Puzzlers puzzle 77 The Lock Mess Monster. as join method executed in the main thread just waits and releases the lock, the daemon thread accquires the lock and set it to run forever.

 

The answer concerns the implementation of Thread.join . It can't be found in the documentation for this method, at least in releases up to and including release 5.0. Internally, Thread.join calls Object.wait on the Thread instance representing the thread being joined. This releases the lock for the duration of the wait. In the case of our program, this allows the timer thread, representing the evil boss, to waltz in and set quittingTime back to false , even though the main thread is currently executing the synchronized quit method. As a consequence, the worker thread never sees that it's quitting time and keeps running forever. The main thread, representing the good boss, never returns from the join method.

 

here, i think the join method though executed by the main thread, and it waits for the main thread to die, but main thread wont go to death until the worker thread finishes its life, is it?

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics