一、生产者消费者模式实现
import java.util.LinkedList;
import java.util.Queue;
public class ProducerConsumerExample {
private static final int BUFFER_SIZE = 5;
private static Queue<Integer> buffer = new LinkedList<>();
public static void main(String[] args) {
Thread producerThread = new Thread(new Producer());
Thread consumerThread = new Thread(new Consumer());
producerThread.start();
consumerThread.start();
try {
producerThread.join();
consumerThread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
static class Producer implements Runnable {
@Override
public void run() {
synchronized (buffer) {
while (true) {
while (buffer.size() == BUFFER_SIZE) {
try {
System.out.println("Buffer is full. Producer is waiting...");
buffer.wait(); // 缓冲区已满,生产者等待
} catch (InterruptedException e) {
e.printStackTrace();
}
}
int item = produceItem();
buffer.add(item);
System.out.println("Producer produced item: " + item);
buffer.notify(); // 唤醒一个等待中的线程&#