java生成一个消费者生成者代码
时间: 2024-04-14 07:30:20 浏览: 27
下面是一个简单的 Java 生产者消费者代码示例:
```java
import java.util.LinkedList;
class ProducerConsumer {
private LinkedList<Integer> buffer = new LinkedList<>();
private int capacity = 5;
public void produce() throws InterruptedException {
int value = 0;
while (true) {
synchronized (this) {
while (buffer.size() == capacity) {
wait();
}
System.out.println("Producer produced: " + value);
buffer.add(value++);
notify();
Thread.sleep(1000);
}
}
}
public void consume() throws InterruptedException {
while (true) {
synchronized (this) {
while (buffer.size() == 0) {
wait();
}
int value = buffer.removeFirst();
System.out.println("Consumer consumed: " + value);
notify();
Thread.sleep(1000);
}
}
}
}
public class Main {
public static void main(String[] args) {
ProducerConsumer pc = new ProducerConsumer();
Thread producerThread = new Thread(() -> {
try {
pc.produce();
} catch (InterruptedException e) {
e.printStackTrace();
}
});
Thread consumerThread = new Thread(() -> {
try {
pc.consume();
} catch (InterruptedException e) {
e.printStackTrace();
}
});
producerThread.start();
consumerThread.start();
}
}
```
上述代码演示了一个简单的生产者消费者模型。生产者线程不断地往共享缓冲区中添加数据,消费者线程不断地从缓冲区中消费数据。通过使用 `synchronized` 关键字和 `wait()`、`notify()` 方法,确保了线程之间的同步和互斥,以避免生产者在缓冲区满时继续生产,消费者在缓冲区空时继续消费的问题。
注意:上述代码只是一个简单示例,实际应用中可能需要更加复杂的逻辑和额外的线程安全措施。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)