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?

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值