2 回答

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

TA貢獻(xiàn)1872條經(jīng)驗(yàn) 獲得超4個(gè)贊
沒有同步,test.printAnotherMessage();因此假設(shè)時(shí)機(jī)正確,它將首先執(zhí)行。4 秒已經(jīng)很多了,應(yīng)該足夠了。
synchronized (test) {
test.printAnotherMessage();
}
Thread.sleep不過,這很少是一個(gè)好的選擇。更合適的方法是
Test test = new Test();
new Thread(() -> {
synchronized (test) {
test.printMessage();
test.notify();
}
}).start();
synchronized (test) {
test.wait();
test.printAnotherMessage();
}
我在這里玩一個(gè)危險(xiǎn)的游戲,因?yàn)槲壹僭O(shè)主線程將進(jìn)入同步塊并在創(chuàng)建另一個(gè)線程并進(jìn)入其同步塊wait() 之前執(zhí)行。這是合理的,因?yàn)閯?chuàng)建線程需要一些時(shí)間。
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();
}
添加回答
舉報(bào)