簡體   English   中英

在Java中調用wait()之后線程做了什么?

[英]What does a thread do after calling wait() in Java?

在多線程程序中,我懷疑當一個線程在wait()時,它不會占用太多的cpu利用率,因此cpu可以交換來處理其他線程。

例如,100個線程一起啟動相同的任務,而50個線程實際執行任務,而其他50個線程等待直到所有50個任務完成。 后一種情況比前者花費的時間少得多。

任何人都可以建議一些關於此的讀物嗎?

wait方法有兩個目的:

  1. 它將告訴當前正在執行的線程進入休眠狀態(不使用任何cpu)。
  2. 它將釋放鎖定,以便其他線程可以喚醒並鎖定。

每當方法在同步塊內部執行某些操作時,塊中的任何內容都必須等待釋放鎖定的對象。

synchronized (lockObject) {
    // someone called notify() after taking the lock on
    // lockObject or entered wait() so now it's my turn

    while ( whatineedisnotready) {
        wait(); // release the lock so others can enter their check
        // now, if there are others waiting to run, they 
        // will have a chance at doing so.
    }
}

必讀:

java已同步

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM