concurrent之并发编程-BlockingQueue

 

1.先简单介绍下java.util.concurrent中的几种常见阻塞队列

(1):BlockingQueue

 BlockingQueue有四个具体的实现类,根据不同需求,选择不同的实现类: 
 ArrayBlockingQueue:规定大小的BlockingQueue,其构造函数必须带一个int参数来指明其大小。其所含的对象是以FIFO(先入先出)顺序排序的。 
LinkedBlockingQueue:大小不定的BlockingQueue,若其构造函数带一个规定大小的参数,生成的BlockingQueue 有大小限制,若不带大小参数,所生成的BlockingQueue的大小由Integer.MAX_VALUE来决定。其所含的对象是以FIFO顺序排序的。
PriorityBlockingQueue:类似于LinkedBlockingQueue,但其所含对象的排序不是FIFO,而是依据对象的自然排序顺序或者是构造函数所带的Comparator决定的顺序。 
SynchronousQueue:特殊的BlockingQueue,对其的操作必须是放和取交替完成的。

其中的LinkedBlockingQueue和SynchronousQueue又是比较常用的。

 

下面以2个例子简单介绍,部分源码如下:

public class BlockingQueueTest {

 public static void main(String[] args) {

  final BlockingQueue<Integer> queues = new LinkedBlockingDeque<Integer>(3);

  final Random random = new Random();


  /**
   * 生产者
   * @author Administrator
   *
   */
  class Producer implements Runnable {
   public void run() {
    while (true) {
     int i = random.nextInt(100);
     // 当队列容量达到时,会自动阻塞
     try {
      queues.put(i);
      if (queues.size() == 3) {
       System.out.println("full");
      }
     } catch (InterruptedException e) {
      e.printStackTrace();
     }
    }
   }
  }

  /**
   * 消费者
   * @author Administrator
   *
   */
  class Consumer implements Runnable {
   public void run() {
    while (true) {
     try {
      // 当队列为空时,也会阻塞
      queues.take();
      Thread.sleep(3000);
     } catch (InterruptedException e) {
      e.printStackTrace();
     }
    }
   }
  }

  new Thread(new Producer()).start();
  new Thread(new Consumer()).start();
 }
}

 

public class SynchronousQueueTest {

 class producer implements Runnable {
  
  private BlockingQueue<String> queues;
  List<String> objects = Arrays.asList("one","two","three");

  public producer(BlockingQueue<String> q) {
   this.queues = q;
  }

  public void run() {
   try {
    for (String s : objects) {
     queues.put(s);
     System.out.println("put:"+s);
    }
    queues.put("done");
   } catch (InterruptedException e) {
    e.printStackTrace();
   }
  }
 }
 
 class consumer implements Runnable {
  
  private BlockingQueue<String> queues;
  
  public consumer(BlockingQueue<String> q) {
   this.queues = q;
  }
  
  public void run() {
   
   String obj;
   
   try {
    while (!((obj = queues.take()).equals("done"))) {
     System.out.println("take:"+obj);
     Thread.sleep(3000);
    }
   } catch (InterruptedException e) {
    e.printStackTrace();
   }
  }
 }

 public static void main(String[] args) {
  
  BlockingQueue<String> bq = new SynchronousQueue<String>();
  
  SynchronousQueueTest sqt = new SynchronousQueueTest();
  
  new Thread(sqt.new producer(bq)).start();
  new Thread(sqt.new consumer(bq)).start();
 }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值