阻塞队列

Posted 林**

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了阻塞队列相关的知识,希望对你有一定的参考价值。

 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 }

 

以上是关于阻塞队列的主要内容,如果未能解决你的问题,请参考以下文章

Java 阻塞队列

Java 阻塞队列

Java 阻塞队列

Java多线程:阻塞队列与等待唤醒机制初探

转: Java并发编程之二十一:并发新特性—阻塞队列和阻塞栈(含代码)

Java之阻塞队列深度剖析