java手写生产者和消费者模式
时间: 2023-11-04 15:04:56 浏览: 168
可以的,生产者和消费者模式是一种常见的多线程编程模式,可以通过使用锁和条件变量来实现线程间的同步和互斥。在Java中,可以使用synchronized关键字和wait/notify方法来实现生产者和消费者模式。生产者线程负责生产数据,并将数据放入共享的缓冲区中,消费者线程负责从缓冲区中取出数据并进行处理。需要注意的是,生产者和消费者线程之间需要进行同步,以避免竞争条件和死锁问题的出现。
相关问题
java手写生产者和消费者模式代码实现
好的,下面是 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();
}
}
}
```
希望可以帮到你,若有需要可以继续提问。接下来请问你想问什么?
阅读全文