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?
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Exception in thread main java.lang. NoClassDefFoundError 오류 해결 방법즉,/home/hadoop/jarfile) 시스템은 Hello World 패키지 아래의class라는 클래스 파일을 실행하고 있다고 오인하여 시스템의 CLASSPATH 아래 (일반적으로 현재 디렉터리를 포함) Hell...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.