java wait() notify()
阿新 • • 發佈:2018-11-06
使用wait方法可以使當前執行緒暫時停止執行
1. 執行緒處於就緒狀態
2. 執行緒所獲得的鎖被釋放,當有別有執行緒呼叫了對應的notify方法時,原執行緒可以重新獲得鎖,並執行。
典型的是生產者與消費者問題。
public class ProducerAndConsumer {
// true 表示生產者不用工作
public static boolean isEmpty = true;
public static Object lock = new Object();
public static void main(String[] args) {
Thread producerThread = new Thread(new Producer());
Thread consumerThread = new Thread(new Consumer());
producerThread.start();
consumerThread.start();
}
}
class Producer implements Runnable {
@Override
public void run() {
synchronized (ProducerAndConsumer.lock) {
while (true) {
if (!ProducerAndConsumer.isEmpty) {
try {
ProducerAndConsumer.lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("producer..." );
ProducerAndConsumer.isEmpty = false;
ProducerAndConsumer.lock.notifyAll();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
class Consumer implements Runnable {
@Override
public void run() {
synchronized (ProducerAndConsumer.lock) {
while (true) {
if (ProducerAndConsumer.isEmpty) {
try {
System.out.println("black is empty");
ProducerAndConsumer.lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("consumer...");
ProducerAndConsumer.isEmpty = true;
ProducerAndConsumer.lock.notifyAll();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}