wait()、notify() 和 notifyAll() 方法是 Java 並發模型不可或缺的一部分。它們屬於 Object 類,這是 Java 中類別層次結構的根。這意味著 Java 中的每個類別都從 Object 類別繼承這些方法。
Object類別是Java中所有類別的超類別。它提供了一組每個類別都繼承的基本方法,包括toString()、equals()和hashCode()。 wait()、notify() 和 notifyAll() 方法也是此類的一部分,使線程能夠通信和協調其活動。
要了解這些方法的工作原理,讓我們來看一些實際範例。
這是一個示範這些方法用法的簡單範例:
class SharedResource { private boolean available = false; public synchronized void consume() throws InterruptedException { while (!available) { wait(); // Wait until the resource is available } // Consume the resource System.out.println("Resource consumed."); available = false; notify(); // Notify that the resource is now unavailable } public synchronized void produce() { // Produce the resource available = true; System.out.println("Resource produced."); notify(); // Notify that the resource is available } } public class Main { public static void main(String[] args) { SharedResource resource = new SharedResource(); Thread producer = new Thread(() -> { try { while (true) { Thread.sleep(1000); // Simulate time to produce resource.produce(); } } catch (InterruptedException e) { e.printStackTrace(); } }); Thread consumer = new Thread(() -> { try { while (true) { resource.consume(); Thread.sleep(2000); // Simulate time to consume } } catch (InterruptedException e) { e.printStackTrace(); } }); producer.start(); consumer.start(); } }
上例中:
您將看到以下輸出,指示生產者和消費者操作:
Resource produced. Resource consumed. ...
此輸出示範了 wait()、notify() 和 notifyAll() 如何協調生產者-消費者互動。
透過了解wait()、notify()和notifyAll()方法屬於哪個類別以及它們如何運作,您可以有效地管理Java 應用程式中的執行緒間通訊。這些方法對於確保執行緒有效地協作和共享資源至關重要。
如果您有任何疑問或需要進一步說明,請隨時在下面發表評論!
閱讀更多文章:wait()、notify() 和 notifyAll() 方法屬於哪個類別?
免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。
Copyright© 2022 湘ICP备2022001581号-3