zoukankan      html  css  js  c++  java
  • BlockingQueue<> 队列的作用

    BlockingQueue<> 队列的作用

    BlockingQueue 实现主要用于生产者-使用者队列

    BlockingQueue 实现主要用于生产者-使用者队列,BlockingQueue 实现是线程安全的。所有排队方法都可以使用内部锁或其他形式的并发控制来自动达到它们的目的

    **这是一个生产者-使用者场景的一个用例。注意,BlockingQueue 可以安全地与多个生产者和多个使用者一起使用 **
    此用例来自jdk文档

    //这是一个生产者类
    class Producer implements Runnable {
       private final BlockingQueue queue;
       Producer(BlockingQueue q) { 
    	   queue = q; 
       }
       public void run() {
         try {
           while(true) { 
    	       queue.put(produce()); 
           }
         } catch (InterruptedException ex) { 
    	     ... handle ...
    	     }
       }
       Object produce() { 
    	   ... 
       }
     }
    
     //这是一个消费者类
     class Consumer implements Runnable {
       private final BlockingQueue queue;
       Consumer(BlockingQueue q) { queue = q; }
       public void run() {
         try {
           while(true) { 
    	       consume(queue.take()); 
           }
         } catch (InterruptedException ex) { 
    	     ... handle ...
         }
       }
       void consume(Object x) { 
    	   ... 
       }
     }
    
     //这是实现类
     class Setup {
       void main() {
         //实例一个非阻塞队列
         BlockingQueue q = new SomeQueueImplementation();
         //将队列传入两个消费者和一个生产者中
         Producer p = new Producer(q);
         Consumer c1 = new Consumer(q);
         Consumer c2 = new Consumer(q);
         new Thread(p).start();
         new Thread(c1).start();
         new Thread(c2).start();
       }
     }
  • 相关阅读:
    228. Summary Ranges
    227. Basic Calculator II
    224. Basic Calculator
    222. Count Complete Tree Nodes
    223. Rectangle Area
    221. Maximal Square
    220. Contains Duplicate III
    219. Contains Duplicate II
    217. Contains Duplicate
    Java编程思想 4th 第4章 控制执行流程
  • 原文地址:https://www.cnblogs.com/wangshouchang/p/6753623.html
Copyright © 2011-2022 走看看