首页 > 其他 > 详细

阻塞队列

时间:2017-12-13 19:04:22      阅读:199      评论:0      收藏:0      [点我收藏+]
 1 package unit;
 2 
 3 import java.util.concurrent.ArrayBlockingQueue;
 4 
 5 /**
 6  * 阻塞队列
 7  * @author 54304
 8  *
 9  */
10 public class BlockingQueue {
11     private int queueSize = 10;
12     private ArrayBlockingQueue<Integer> queue = new ArrayBlockingQueue<Integer>(queueSize);
13     int m = 0;
14     int n = 0;
15     int k = 0;
16     public static void main(String[] args) throws InterruptedException  {
17         BlockingQueue test = new BlockingQueue();
18         Producer producer = test.new Producer();
19         Consumer consumer = test.new Consumer();
20         
21         producer.start();
22         consumer.start();
23     }
24      
25     class Consumer extends Thread{
26          
27         @Override
28         public void run() {
29             consume();
30         }
31          
32         private void consume() {
33             while(true){
34                 try {
35                     queue.take();
36                     Thread.sleep(1000);
37                     System.out.println("队列有: "+queue.size()+" 个 元素"+"  编号"+ ++m + " 减少"+ "   减少次数:"+ ++n);
38                 } catch (InterruptedException e) {
39                     e.printStackTrace();
40                 }
41             }
42         }
43     }
44      
45     class Producer extends Thread{
46          
47         @Override
48         public void run() {
49             produce();
50         }
51          
52         private void produce() {
53             for(int i=0; i<10; i++){
54                 try {
55                     queue.put(1);
56                     Thread.sleep(1000);
57                     System.out.println("队列有: "+queue.size()+" 个 元素"+"  编号"+ ++m + " 添加"+ "   添加次数:"+ ++k);
58                 } catch (InterruptedException e) {
59                     e.printStackTrace();
60                 }
61             }
62         }
63     }
64 }

 

阻塞队列

原文:http://www.cnblogs.com/redhat0019/p/8034182.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!