2 回答

TA貢獻1827條經驗 獲得超8個贊
printAnotherMessage
在此示例中,休眠 5 秒的同步塊之間沒有同步,這就是主線程休眠 1 秒然后main Thread
無需任何等待即可打印的原因。
您可能打算創建printAnotherMessage
一個同步方法。在這種情況下,主線程將等待,直到另一個線程完成測試對象上同步塊的執行。

TA貢獻1872條經驗 獲得超4個贊
沒有同步,test.printAnotherMessage();因此假設時機正確,它將首先執行。4 秒已經很多了,應該足夠了。
synchronized (test) {
test.printAnotherMessage();
}
Thread.sleep不過,這很少是一個好的選擇。更合適的方法是
Test test = new Test();
new Thread(() -> {
synchronized (test) {
test.printMessage();
test.notify();
}
}).start();
synchronized (test) {
test.wait();
test.printAnotherMessage();
}
我在這里玩一個危險的游戲,因為我假設主線程將進入同步塊并在創建另一個線程并進入其同步塊wait() 之前執行。這是合理的,因為創建線程需要一些時間。
Test test = new Test();
new Thread(() -> {
try {
// a lot of time to let the main thread execute wait()
Thread.sleep(500);
synchronized (test) {
test.printMessage();
test.notify();
}
} catch (InterruptedException e) {}
}).start();
synchronized (test) {
test.wait();
test.printAnotherMessage();
}
添加回答
舉報