LinkedBlockingQueue队列的使用

这是LinkedBlockingQueue的使用示例

有一个生产者往里面写消息,生产者写完休眠500ms

有一个消费者往里面消耗消息

具体如下:

第一步,生产者

 1 public class Producer {
 2     private LinkedBlockingQueue<String> queue;
 3     public Producer(LinkedBlockingQueue<String> q){
 4         queue = q;
 5     }
 6 
 7     public void produce(){
 8         String message = "消息[" + System.currentTimeMillis() + "]";
 9         try {
10             queue.put(message);
11         }catch (InterruptedException e){
12             System.out.println("生产者[" + Thread.currentThread().getName() + "], 存放出错 : " + e.getMessage());
13         }
14         System.out.println("生产者[" + Thread.currentThread().getName() + "],生产消息:" + message);
15     }
16 }

第二步,消费者

 1 public class Consumer {
 2     private LinkedBlockingQueue<String> queue;
 3     public Consumer(LinkedBlockingQueue<String> q){
 4         queue = q;
 5     }
 6 
 7     public void consume(){
 8         String message = null;
 9         try {
10             message = queue.take();
11         }catch (InterruptedException e){
12             System.out.println("消费者[" + Thread.currentThread().getName() + "],存放消息失败:" + e.getMessage());
13         }
14         System.out.println("消费者[" + Thread.currentThread().getName() + "],获取消息:"  + message);
15     }
16 }

第三步,运行

 1 public class Main {
 2     public static void main(String[] args) throws Exception{
 3         ExecutorService exeService = Executors.newFixedThreadPool(100);
 4         LinkedBlockingQueue<String> queue = new LinkedBlockingQueue<>(10000);
 5         // 放90个生产者
 6         for(int i = 0; i < 90; i++){
 7             exeService.execute(() -> {
 8                 Producer p = new Producer(queue);
 9                 while(true) {
10                     p.produce();
11                     try {
12                         Thread.sleep(500);
13                     } catch (InterruptedException e) {
14                     }
15                 }
16             });
17         }
18         // 放10个消费者
19         for(int i = 0; i < 10; i++){
20             exeService.execute(() -> {
21                 Consumer c = new Consumer(queue);
22                 while(true) {
23                     c.consume();
24                 }
25             });
26         }
27         new CountDownLatch(1).await();
28     }
29 }

结果如下所示:

 

posted @ 2022-04-23 16:57  哦客源  阅读(1275)  评论(0)    收藏  举报