f*n 发帖数: 254 | 1 77th from Java Puzzlers book.
Code is as following:
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() {
quittingTime = true;
}
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();
}
}
按分析,Thread.join()调用Object.wait(),解锁了quittingTime,设成false,那么
good boss会进入死循环出不来。
但是在JDK8下,反复运行,没有一次造成死循环。请问为什么。谢谢。 | F****n 发帖数: 3271 | 2 Because both good & evil bosses are in synchronized block,
The evil boss will not be able to obtain the lock until join() finish.
On the other hand, the worker thread is not in synchronized block and
it can access quittingTime and terminate.
【在 f*n 的大作中提到】 : 77th from Java Puzzlers book. : Code is as following: : 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!");
|
|