在Java中,線程等待通??梢酝ㄟ^使用wait()和notify()方法來實現資源共享。wait()方法用于使當前線程等待并釋放對象的鎖,而notify()方法用于喚醒等待中的線程。下面是一個簡單的示例代碼來展示如何優雅地使用wait()和notify()方法進行資源共享:
public class Resource {
private int value;
private boolean isSet = false;
public synchronized void setValue(int value) {
while (isSet) {
try {
wait();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
this.value = value;
isSet = true;
System.out.println("Set value: " + value);
notify();
}
public synchronized int getValue() {
while (!isSet) {
try {
wait();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
isSet = false;
System.out.println("Get value: " + value);
notify();
return value;
}
public static void main(String[] args) {
Resource resource = new Resource();
Thread producerThread = new Thread(() -> {
for (int i = 0; i < 5; i++) {
resource.setValue(i);
}
});
Thread consumerThread = new Thread(() -> {
for (int i = 0; i < 5; i++) {
resource.getValue();
}
});
producerThread.start();
consumerThread.start();
}
}
在上面的示例中,Resource類代表一個共享資源,setValue()方法用于設置值,getValue()方法用于獲取值。在setValue()和getValue()方法中使用了synchronized關鍵字來保證線程安全,并通過wait()和notify()方法來實現線程等待和喚醒。通過這種方式,可以實現線程之間的資源共享和協作。