wait()方法是Java中的一個同步機制,用于讓當前線程等待,直到其他線程調用同一個對象的notify()或notifyAll()方法。在使用wait()方法時,需要遵循以下步驟:
確保線程間通信:wait()方法通常在多線程環境下使用,確保線程間正確通信是非常重要的。這通常涉及到共享數據(如變量、對象等)的訪問和修改。
在同步代碼塊或方法中使用wait():為了確保線程安全,需要在同步代碼塊或方法中使用wait()。這可以通過在方法聲明中添加synchronized關鍵字來實現。
調用wait()前檢查條件:在調用wait()之前,需要檢查線程等待的條件是否滿足。如果不滿足,線程將立即退出wait()狀態。
使用notify()或notifyAll()喚醒線程:當其他線程修改了共享數據并滿足等待線程的條件時,需要調用notify()或notifyAll()方法喚醒等待的線程。notify()只喚醒一個等待線程,而notifyAll()會喚醒所有等待線程。
下面是一個簡單的示例:
public class Example {
private int counter = 0;
public synchronized void increment() {
counter++;
if (counter < 10) {
System.out.println(Thread.currentThread().getName() + " incremented counter to " + counter);
notify(); // 喚醒等待的線程
} else {
System.out.println(Thread.currentThread().getName() + " reached 10, notifying all threads.");
notifyAll(); // 喚醒所有等待的線程
}
}
public synchronized void waitUntilCounterLessThan10() throws InterruptedException {
while (counter >= 10) {
System.out.println(Thread.currentThread().getName() + " waiting for counter to be less than 10.");
wait(); // 等待被喚醒
}
System.out.println(Thread.currentThread().getName() + " counter is now less than 10.");
}
public static void main(String[] args) {
Example example = new Example();
Thread t1 = new Thread(() -> {
try {
example.waitUntilCounterLessThan10();
} catch (InterruptedException e) {
e.printStackTrace();
}
}, "Thread-1");
Thread t2 = new Thread(() -> {
try {
example.increment();
} catch (InterruptedException e) {
e.printStackTrace();
}
}, "Thread-2");
t1.start();
t2.start();
}
}
在這個示例中,我們有一個名為Example的類,其中包含兩個同步方法:increment()和waitUntilCounterLessThan10()。increment()方法在計數器達到10時調用notifyAll()喚醒所有等待的線程,而在計數器小于10時調用notify()喚醒一個等待的線程。waitUntilCounterLessThan10()方法使用wait()等待計數器小于10。在main()方法中,我們創建了兩個線程,一個等待計數器小于10,另一個遞增計數器。