我有從 main 呼叫的等待通知應用程式的示例:
public class Handler {
public void producer () throws InterruptedException {
Thread.sleep(1000);
synchronized(this) {
System.out.println("Producer started ######...");
wait();
System.out.println("Proceed running in current thread after notification and 5s sleep in consumer tread");
}
}
public void consumer() throws InterruptedException {
Thread.sleep(2000);
synchronized(this) {
System.out.println("Consumer started #####...");
notify();
Thread.sleep(5000);
}
}
}
和呼叫者
public class ThreadRunner {
public static void main(String[] args) {
Handler handler = new Handler();
Thread thread1 = new Thread(() -> {
try {
handler.producer();
} catch (InterruptedException e) {
e.printStackTrace();
}
});
Thread thread2 = new Thread(() -> {
try {
handler.consumer();
} catch (InterruptedException e) {
e.printStackTrace();
}
});
thread1.start();
thread2.start();
try {
thread1.join(1);
thread2.join(1);
} catch (InterruptedException e) {
System.out.println("exception");
}
}
}
正如我所期望的那樣,當我加入(1)到執行緒并等待它們只死 1 磨機時,應該列印“例外”訊息,但它們的睡眠時間不止于此。我錯過了什么?
uj5u.com熱心網友回復:
join(1) 有 3 種“退出”方式:
- 您呼叫的執行緒
join結束,在這種情況下,您的呼叫join(1)通過回傳停止運行。 - 某個地方的一些代碼(只有代碼可以做到,例如用戶按下 CTRL C 或其他什么東西永遠不會導致這種情況)
.interrupt()在您的執行緒上呼叫;join(1)通過投擲停止奔跑InterruptedException。 - 1 毫秒過去了,在這種情況下
join(1)通過回傳停止運行。
顯然,如果時間用完,您的印象是 join 方法通過拋出 InterruptedEx 退出。它不是。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/349077.html
上一篇:使用memcpy和mmap復制目錄中的檔案強制所有檔案為1Byte
下一篇:Java執行緒安全問題
