我是靠谱客的博主 香蕉手机,这篇文章主要介绍多线程Demo-ArrayBlockingQueue阻塞队列,现在分享给大家,希望可以做个参考。

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
package Thread; import java.util.Random; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.TimeUnit; public class BlockingQueueTest { public static void main(String[] args) { final ArrayBlockingQueue<Integer> queue = new ArrayBlockingQueue<>(3); for(int i=0; i<10; i++){ new Thread(){ @Override public void run() { try { System.out.println(Thread.currentThread().getName() + "------放----------开始放数据,当前队列有"+queue.size()); queue.put(1); System.out.println(Thread.currentThread().getName() + "------放----------完成放数据,当前队列有"+queue.size()); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }.start(); } for(int i=0; i<10; i++){ new Thread(){ @Override public void run() { try { System.out.println(Thread.currentThread().getName() + "------取----------开始取数据,当前队列有"+queue.size()); TimeUnit.SECONDS.sleep(new Random().nextInt(5)); queue.take(); System.out.println(Thread.currentThread().getName() + "------取----------完成取数据,当前队列有"+queue.size()); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }.start(); } } }


附录


复制代码
1
线程安全队列另外还提供了
复制代码
1
SynchronousQueue:其中每个插入操作必须等待另一个线程的对应移除操作 ,反之亦然。同步队列没有任何内部容量,甚至连一个队列的容量都没有。不能在同步队列上进行 peek,因为仅在试图要移除元素时,该元素才存在;除非另一个线程试图移除某个元素,否则也不能(使用任何方法)插入元素;也不能迭代队列,因为其中没有元素可用于迭代。队列的 是尝试添加到队列中的首个已排队插入线程的元素;如果没有这样的已排队线程,则没有可用于移除的元素并且 poll() 将会返回 null。对于其他 Collection 方法(例如 contains),SynchronousQueue 作为一个空 collection。此队列不允许 null 元素。 


队列更多查看:http://blog.csdn.net/ghsau/article/details/8108292

最后

以上就是香蕉手机最近收集整理的关于多线程Demo-ArrayBlockingQueue阻塞队列的全部内容,更多相关多线程Demo-ArrayBlockingQueue阻塞队列内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(86)

评论列表共有 0 条评论

立即
投稿
返回
顶部