BlockingQueue 生产者-消费者

本文介绍了如何使用Java中的BlockingQueue实现多线程环境下的生产消费模式,通过创建Fetcher和Indexer类分别代表生产者和消费者,并使用ArrayBlockingQueue作为队列,展示了线程之间的同步和等待机制。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

本例介绍一个特殊的队列:BlockingQueue,如果BlockingQueue是空的,从BlockingQueue取东西的操作将会被阻断进入等待状态,直到BlockingQueue进了东西才会被唤醒,同样,如果BlockingQueue是满的,任何试图往里存东西的操作也会被阻断进入等待状态,直到BlockingQueue里有空间时才会被唤醒继续操作。
本例再次实现前面介绍的篮子程序,不过这个篮子中最多能放得苹果数不是1,可以随意指定。当篮子满时,生产者进入等待状态,当篮子空时,消费者等待。

BlockingQueue定义的常用方法如下:
add(anObject):把anObject加到BlockingQueue里,如果BlockingQueue可以容纳,则返回true,否则抛出异常。
offer(anObject):表示如果可能的话,将anObject加到BlockingQueue里,即如果BlockingQueue可以容纳,则返回true,否则返回false。
put(anObject):把anObject加到BlockingQueue里,如果BlockingQueue没有空间,则调用此方法的线程被阻断直到BlockingQueue里有空间再继续。
poll(time):取走BlockingQueue里排在首位的对象,若不能立即取出,则可以等time参数规定的时间,取不到时返回null。
take():取走BlockingQueue里排在首位的对象,若BlockingQueue为空,阻断进入等待状态直到BlockingQueue有新的对象被加入为止。

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

LinkedBlockingQueue和ArrayBlockingQueue比较起来,它们背后所用的数据结构不一样,导致LinkedBlockingQueue的数据吞吐量要大于ArrayBlockingQueue,但在线程数量很大时其性能的可预见性低于ArrayBlockingQueue。

Java代码 收藏代码
  1. <spanstyle="font-size:small;">packagecom.yoyosys.smartstorage.consumer;
  2. importjava.util.concurrent.BlockingQueue;
  3. /**
  4. *to-do.
  5. *
  6. *@authorDenghaiping
  7. *@version1.0
  8. */
  9. publicclassFetcherimplementsRunnable
  10. {
  11. @SuppressWarnings("unused")
  12. privateBlockingQueue<String>queue=null;
  13. publicFetcher(BlockingQueue<String>queue)
  14. {
  15. this.queue=queue;
  16. }
  17. publicvoidrun()
  18. {
  19. try{
  20. while(true){
  21. queue.put("segment-name-"+i);
  22. System.out.println("ThreadName:"+Thread.currentThread().getName()+"抓取完成");
  23. }
  24. }catch(InterruptedExceptionex){
  25. ex.printStackTrace();
  26. }
  27. }
  28. }
  29. </span>

Java代码 收藏代码
  1. <spanstyle="font-size:small;">*/
  2. packagecom.yoyosys.smartstorage.consumer;
  3. importjava.util.concurrent.ArrayBlockingQueue;
  4. importjava.util.concurrent.BlockingQueue;
  5. /**
  6. *to-do.
  7. *
  8. *@authorDenghaiping
  9. *@version1.0
  10. */
  11. publicclassIndexerimplementsRunnable
  12. {
  13. privateBlockingQueue<String>queue;
  14. publicIndexer(BlockingQueue<String>queue)
  15. {
  16. this.queue=queue;
  17. }
  18. publicvoidrun()
  19. {
  20. try{
  21. while(true){
  22. Thread.sleep(1000);
  23. Stringname=queue.take();
  24. System.out.println("ThreadName:"+Thread.currentThread().getName()+"索引创建完成"+name);
  25. }
  26. }catch(InterruptedExceptionex){
  27. ex.printStackTrace();
  28. }
  29. }
  30. }
  31. </span>

Java代码 收藏代码
  1. <spanstyle="font-size:small;">packagecom.yoyosys.smartstorage.consumer;
  2. importjava.util.concurrent.*;
  3. /**
  4. *to-do.
  5. *
  6. *@authorDenghaiping
  7. *@version1.0
  8. */
  9. publicclassTestConsumer
  10. {
  11. privatestaticBlockingQueue<String>queue=newArrayBlockingQueue<String>(10);
  12. publicstaticvoidmain(String[]args)
  13. {
  14. ExecutorServiceservice=Executors.newCachedThreadPool();
  15. Fetcherproducer=newFetcher(queue);
  16. Indexerconsumer=newIndexer(queue);
  17. Indexerconsumer1=newIndexer(queue);
  18. service.submit(producer);
  19. service.submit(consumer);
  20. service.submit(consumer1);
  21. //程序运行5s后,所有任务停止
  22. try{
  23. Thread.sleep(5000);
  24. }catch(InterruptedExceptione){
  25. e.printStackTrace();
  26. }
  27. //service.shutdownNow();
  28. }
  29. }
  30. </span>


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值