Java实现生产者与消费者模式

  生产者不断向队列中添加数据,消费者不断从队列中获取数据。如果队列满了,则生产者不能添加数据;如果队列为空,则消费者不能获取数据。借助实现了BlockingQueue接口的LinkedBlockingQueue来模拟同步。

 1 import java.util.Random;
 2 import java.util.concurrent.BlockingQueue;
 3 import java.util.concurrent.LinkedBlockingQueue;
 4 
 5 /**
 6  * 生产者消费者模式:使用{@link java.util.concurrent.BlockingQueue}实现
 7  */
 8 public class Main{
 9     private static final int CAPACITY = 5;
10 
11     public static void main(String args[]){
12         BlockingQueue<Integer> blockingQueue = new LinkedBlockingQueue<>(CAPACITY);
13 
14         Thread producer1 = new Producer("P-1", blockingQueue, CAPACITY);
15         Thread producer2 = new Producer("P-2", blockingQueue, CAPACITY);
16         Thread consumer1 = new Consumer("C1", blockingQueue, CAPACITY);
17         Thread consumer2 = new Consumer("C2", blockingQueue, CAPACITY);
18         Thread consumer3 = new Consumer("C3", blockingQueue, CAPACITY);
19 
20         producer1.start();
21         producer2.start();
22         consumer1.start();
23         consumer2.start();
24         consumer3.start();
25     }
26 
27     /**
28      * 生产者
29      */
30     public static class Producer extends Thread{
31         private BlockingQueue<Integer> blockingQueue;
32         String name;
33         int maxSize;
34         int i = 0;
35 
36         public Producer(String name, BlockingQueue<Integer> queue, int maxSize){
37             super(name);
38             this.name = name;
39             this.blockingQueue = queue;
40             this.maxSize = maxSize;
41         }
42 
43         @Override
44         public void run(){
45             while(true){
46                 try {
47                     blockingQueue.put(i);
48                     System.out.println("[" + name + "] Producing value : " + i);
49                     i++;
50 
51                     //暂停最多1秒
52                     Thread.sleep(new Random().nextInt(1000));
53                 } catch (InterruptedException e) {
54                     e.printStackTrace();
55                 }
56             }
57 
58         }
59     }
60 
61     /**
62      * 消费者
63      */
64     public static class Consumer extends Thread{
65         private BlockingQueue<Integer> blockingQueue;
66         String name;
67         int maxSize;
68 
69         public Consumer(String name, BlockingQueue<Integer> queue, int maxSize){
70             super(name);
71             this.name = name;
72             this.blockingQueue = queue;
73             this.maxSize = maxSize;
74         }
75 
76         @Override
77         public void run(){
78             while(true){
79                 try {
80                     int x = blockingQueue.take();
81                     System.out.println("[" + name + "] Consuming : " + x);
82 
83                     //暂停最多1秒
84                     Thread.sleep(new Random().nextInt(1000));
85                 } catch (InterruptedException e) {
86                     e.printStackTrace();
87                 }
88             }
89         }
90     }
91 }

  输出结果:

   

 

  参考资料

  【Java】生产者消费者模式的实现

转载于:https://www.cnblogs.com/WJQ2017/p/9518962.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
生产者消费者模式是一种常见的多线程编程模式,可以用于解决生产者消费者之间的数据交换问题。在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。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值