亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

為什么另一個線程在同步部分尚未完成時可以訪問阻塞對象?

為什么另一個線程在同步部分尚未完成時可以訪問阻塞對象?

夢里花落0921 2023-08-09 17:26:34
消息“main Thread”在消息“new Thread”之前打印,盡管消息“new Thread”的方法位于包含 print* 方法的對象的同步部分中。    Test test = new Test();    new Thread(() -> {        try {            synchronized (test) {                Thread.sleep(5000);                test.printMessage();            }        } catch (InterruptedException e) {}    }).start();    Thread.sleep(1000);    test.printAnotherMessage();}public void printMessage() {    System.out.println("new Thread");}public void printAnotherMessage() {    System.out.println("main Thread");}}
查看完整描述

2 回答

?
斯蒂芬大帝

TA貢獻1827條經驗 獲得超8個贊

printAnotherMessage在此示例中,休眠 5 秒的同步塊之間沒有同步,這就是主線程休眠 1 秒然后main Thread無需任何等待即可打印的原因。

您可能打算創建printAnotherMessage一個同步方法。在這種情況下,主線程將等待,直到另一個線程完成測試對象上同步塊的執行。


查看完整回答
反對 回復 2023-08-09
?
守著一只汪

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();

}


查看完整回答
反對 回復 2023-08-09
  • 2 回答
  • 0 關注
  • 146 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號