由买买提看人间百态

boards

本页内容为未名空间相应帖子的节选和存档,一周内的贴子最多显示50字,超过一周显示500字 访问原贴
Java版 - 问一个lock的puzzle
相关主题
怎么synchronize时间捏新手问个multi-threading关于synchronized和volatile的问题
如何让两个socket并行执行threadJDK7
这个Timer不退出是怎么回事儿?JDK8要出来了?
java synchronized 问题 (转载)最近node.js real time web 很火
a fun coding questionJAX Innovation Awards 影响有多大
发现 synchronized 的一个问题工厂模式
synchronization for countersTalk a little more about How to lock a file
synchronization 锁住了什么?请教一个多线程lock机制的问题
相关话题的讨论汇总
话题: worker话题: void话题: public
进入Java版参与讨论
1 (共1页)
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!");

1 (共1页)
进入Java版参与讨论
相关主题
请教一个多线程lock机制的问题a fun coding question
Timer and TimerTask发现 synchronized 的一个问题
HashMap cachesynchronization for counters
Apply lock on a class.synchronization 锁住了什么?
怎么synchronize时间捏新手问个multi-threading关于synchronized和volatile的问题
如何让两个socket并行执行threadJDK7
这个Timer不退出是怎么回事儿?JDK8要出来了?
java synchronized 问题 (转载)最近node.js real time web 很火
相关话题的讨论汇总
话题: worker话题: void话题: public