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();}}}}}
}