JUC:BlockingQueue接口

java.util.concurrent 包(a.k.a.JUC)下的 一个接口,用来实现 阻塞队列。

 

其中,cnblogs

ArrayBlockingQueue 初始化时 需要 提供容量信息,超过容量时,添加元素失败,是 有界(界限)容器。

LinkedBlockingQueue 初始化时 可以不提供容量信息;不提供时,容器是 无界的,,添加时,同 上面的 ArrayBlockingQueue 一样有限制。

PriorityBlockingQueue 初始化时 传入的整数是 initialCapacity ,而不是 容量!是 无界的,可以一直添加。cnblo

 

// PriorityBlockingQueue 的 4个构造函数,,注意是 initialCapacity
public PriorityBlockingQueue();
public PriorityBlockingQueue(int initialCapacity);
public PriorityBlockingQueue(int initialCapacity,
                                 Comparator<? super E> comparator);
public PriorityBlockingQueue(Collection<? extends E> c);

 

SynchronousQueue 不存储元素,只用来在 两个线程间 传递元素——A线程等待(take()——没有值时卡住),B线程调用add(val) 传值给 A线程。

 

重要方法:

add, offer, put,

take, poll, drainTo 

 

示例代码:

 1 // 随机数对象
 2 private static Random rand = new Random(System.currentTimeMillis());
 3 // 输出内容对象
 4 private static Consumer<Object> oc = System.out::println;
 5 
 6 // 测试 BlockingQueue
 7 public static void testBlockingQueue() {
 8     BlockingQueue<Integer> bq1 = new ArrayBlockingQueue<>(2); // 1
 9     //BlockingQueue<Integer> bq1 = new LinkedBlockingQueue<>(2); // 2
10     //BlockingQueue<Integer> bq1 = new PriorityBlockingQueue<>(2); // 3
11 
12     oc.accept(bq1.add(rand.nextInt(1000))); // 返回 true
13     oc.accept(bq1.add(rand.nextInt(1000))); // 返回 true
14 //    oc.accept(bq1.add(rand.nextInt(1000))); // 1、2会发生异常
15 
16     oc.accept(bq1.offer(rand.nextInt(1000))); // add 改为 offer 不会添加成功,不会异常,返回false
17     oc.accept("bq1=" + bq1);
18     
19     oc.accept("test SynchronousQueue:");
20     SynchronousQueue<Integer> sq = new SynchronousQueue<>();
21     //oc.accept(sq.add(rand.nextInt(5))); // 发生异常
22 
23     // 启动线程 一个一个添加(传递)元素
24     new Thread(()->{
25         for (int i=0; i<5; i++) {
26             try {
27                 TimeUnit.SECONDS.sleep(2); // 必须先休眠,等待主线程take
28             } catch (InterruptedException e) {
29                 e.printStackTrace();
30             }
31             
32             oc.accept("sq 1=" + sq + ", i=" + i);
33             oc.accept("添加:");
34             sq.add(rand.nextInt());
35             oc.accept("sq 2=" + sq);
36         }
37     }).start();
38         
39     
40     oc.accept(sq);
41     try {
42         for (int i=0; i<5; i++) {
43             // 主线程 take 5次
44             oc.accept((i + 1) + "-" + sq.take());
45         }
46     } catch (InterruptedException e) {
47         e.printStackTrace();
48     }
49 }

 

参考文档:cnblogs

1、https://blog.csdn.net/ai_xiangjuan/article/details/80153188

2、https://blog.csdn.net/Kincym/article/details/78859161

 

posted @ 2021-04-21 15:25  快乐的欧阳天美1114  阅读(65)  评论(0)    收藏  举报