在 Java 中,如何讓執行緒互相通訊?


執行緒間通訊涉及到執行緒之間的互相通訊。有三種方法可用於在 Java 中實現執行緒間通訊。

wait()

此方法導致當前執行緒釋放鎖。此操作會持續到特定時間過去或者另一個執行緒針對此物件呼叫 notify() 或 notifyAll() 方法。

notify()

此方法喚醒當前物件監視器上的多個執行緒中的一個執行緒。執行緒的選擇是任意的。

notifyAll()

此方法喚醒當前物件監視器上的所有執行緒。

示例

class BankClient {
   int balAmount = 5000;
   synchronized void withdrawMoney(int amount) {
      System.out.println("Withdrawing money");
      balAmount -= amount;
      System.out.println("The balance amount is: " + balAmount);
   }
   synchronized void depositMoney(int amount) {
      System.out.println("Depositing money");
      balAmount += amount;
      System.out.println("The balance amount is: " + balAmount);
      notify();
   }
}
public class ThreadCommunicationTest {
   public static void main(String args[]) {
      final BankClient client = new BankClient();
      new Thread() {
         public void run() {
            client.withdrawMoney(3000);
         }
      }.start();
      new Thread() {
         public void run() {
           client.depositMoney(2000);
         }
      }.start();
   }
}

輸出

Withdrawing money
The balance amount is: 2000
Depositing money
The balance amount is: 4000 

更新時間: 2023 年 11 月 29 日

5K+ 次瀏覽

開啟您的 職業生涯

完成課程以獲得認證

開始
廣告
© . All rights reserved.