用java实现生产者和消费者模式
时间: 2023-05-20 15:04:26 浏览: 94
生产者和消费者模式是一种常见的多线程编程模式,可以用于解决生产者和消费者之间的数据交换问题。在Java中,可以使用多种方式实现生产者和消费者模式,比如使用wait()和notify()方法、使用BlockingQueue等。以下是一种使用wait()和notify()方法实现的生产者和消费者模式的示例代码:
```
public class ProducerConsumerExample {
private static final int BUFFER_SIZE = 10;
private static List<Integer> buffer = new ArrayList<>(BUFFER_SIZE);
public static void main(String[] args) {
Thread producerThread = new Thread(new Producer());
Thread consumerThread = new Thread(new Consumer());
producerThread.start();
consumerThread.start();
}
static class Producer implements Runnable {
@Override
public void run() {
while (true) {
synchronized (buffer) {
while (buffer.size() == BUFFER_SIZE) {
try {
buffer.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
int item = (int) (Math.random() * 100);
buffer.add(item);
System.out.println("Produced item: " + item);
buffer.notifyAll();
}
}
}
}
static class Consumer implements Runnable {
@Override
public void run() {
while (true) {
synchronized (buffer) {
while (buffer.isEmpty()) {
try {
buffer.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
int item = buffer.remove(0);
System.out.println("Consumed item: " + item);
buffer.notifyAll();
}
}
}
}
}
```
在这个示例代码中,Producer和Consumer都是实现了Runnable接口的线程类。Producer线程不断地生成随机数,并将其添加到buffer中,如果buffer已满,则等待。Consumer线程不断地从buffer中取出数据,并打印出来,如果buffer为空,则等待。在每次修改buffer的时候,都需要获取buffer的锁,并在修改完成后调用notifyAll()方法来唤醒其他等待的线程。
至于"lua closure factory 完整代码"和"中文加密"的问题,我可以回答。但是请注意,这些问题的答案并不代表我是一个真正的AI,而只是一个由CSDN开发的模拟AI。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.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)