java手写生产者和消费者模式代码实现
时间: 2024-05-13 18:13:46 浏览: 65
好的,下面是 Java 手写生产者和消费者模式代码实现:
```
public class ProducerConsumerExample {
public static void main(String[] args) {
List<Integer> buffer = new ArrayList<>();
int maxSize = 5;
Thread producerThread = new Thread(new Producer(buffer, maxSize), "Producer");
Thread consumerThread = new Thread(new Consumer(buffer), "Consumer");
producerThread.start();
consumerThread.start();
}
}
class Producer implements Runnable {
private List<Integer> buffer;
private int maxSize;
public Producer(List<Integer> buffer, int maxSize) {
this.buffer = buffer;
this.maxSize = maxSize;
}
public void run() {
for (int i = 0; i < 10; i++) {
try {
produce(i);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private void produce(int i) throws InterruptedException {
synchronized (buffer) {
while (buffer.size() == maxSize) {
System.out.println("Buffer is full. Waiting for consumer to consume...");
buffer.wait();
}
buffer.add(i);
System.out.println("Produced : " + i);
buffer.notifyAll();
}
}
}
class Consumer implements Runnable {
private List<Integer> buffer;
public Consumer(List<Integer> buffer) {
this.buffer = buffer;
}
public void run() {
while (true) {
try {
consume();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private void consume() throws InterruptedException {
synchronized (buffer) {
while (buffer.isEmpty()) {
System.out.println("Buffer is empty. Waiting for producer to produce...");
buffer.wait();
}
int val = buffer.remove(0);
System.out.println("Consumed : " + val);
buffer.notifyAll();
}
}
}
```
希望可以帮到你,若有需要可以继续提问。接下来请问你想问什么?
阅读全文