wait(), notify(), 和 notifyAll()
是 Java 中用于線程間通信和同步的方法,它們都是 Object 類中的方法,而非 Thread 類的方法。這些方法通常與 synchronized 關鍵字一起使用,用于實現線程之間的協作和互斥訪問共享資源。
關于生產者-消費者的例子:
import java.util.LinkedList;
import java.util.Queue;public class ProducerConsumerExample {private static final int MAX_CAPACITY = 5;private static final Queue<Integer> buffer = new LinkedList<>();public static void main(String[] args) {Thread producerThread = new Thread(new Producer(), "ProducerThread");Thread consumerThread = new Thread(new Consumer(), "ConsumerThread");producerThread.start();consumerThread.start();}static class Producer implements Runnable {@Overridepublic void run() {int value = 0;while (true) {synchronized (buffer) {try {while (buffer.size() == MAX_CAPACITY) {System.out.println("Buffer is full, producer is waiting...");buffer.wait();}System.out.println("Producing value: " + value);buffer.offer(value++);buffer.notifyAll();Thread.sleep(1000); // 模擬生產過程} catch (InterruptedException e) {e.printStackTrace();}}}}}static class Consumer implements Runnable {@Overridepublic void run() {while (true) {synchronized (buffer) {try {while (buffer.isEmpty()) {System.out.println("Buffer is empty, consumer is waiting...");buffer.wait();}int consumedValue = buffer.poll();System.out.println("Consuming value: " + consumedValue);buffer.notifyAll();Thread.sleep(1000); // 模擬消費過程} catch (InterruptedException e) {e.printStackTrace();}}}}}
}