ArrayBlockingQueue使用
来源:互联网 发布:阿里云国际版网址 编辑:程序博客网 时间:2024/04/30 13:08
【参考文章:】http://www.cnblogs.com/belen/archive/2012/04/13/2446019.html
BlockingQueue 定义了一个FIFO的队列接口,。试图向已满队列中放入元素会导致放入操作受阻塞;试图从空队列中检索元素将导致
类似阻塞。
ArrayBlockingQueue是此接口的一个实现。
API:http://www.ostools.net/uploads/apidocs/jdk-zh/java/util/concurrent/ArrayBlockingQueue.html
下面是一个例子: 两个线程,thread1, thread2, 各自维护队列queue1, queue2, 初始时queue2不阻塞, 之后两个 thread
在自己的queue中加入元素,在对方的queue中take元素,进行十次这样的操作。
import java.util.concurrent.ArrayBlockingQueue;import java.util.concurrent.BlockingQueue;public class ArrayBlockingCommunication {public static void main(String[] args) {final Business bussiness = new Business();new Thread(new Runnable() {public void run() {for (int i = 0; i < 10; i++) {bussiness.methodForThread1(i);}}}).start();new Thread(new Runnable() {public void run() {for (int i = 0; i < 10; i++) {bussiness.methodForThread2(i);}}}).start();}static class Business {BlockingQueue <Integer> queue1 = new ArrayBlockingQueue <Integer> (1);BlockingQueue <Integer> queue2 = new ArrayBlockingQueue <Integer> (1);{try {queue2.put(1);} catch (InterruptedException e) {e.printStackTrace();}}public void methodForThread1(int i) {try {queue1.put(1);System.out.println("Thread " + Thread.currentThread().getName() + " is blocking");} catch (InterruptedException e) {e.printStackTrace();}System.out.println("Thread " + Thread.currentThread().getName() + " is running : " + i);try {queue2.take();} catch (InterruptedException e) {e.printStackTrace();}}public void methodForThread2(int i) {try {queue2.put(1);System.out.println("Thread " + Thread.currentThread().getName() + " is blocking");} catch (InterruptedException e) {e.printStackTrace();}System.out.println("Thread " + Thread.currentThread().getName() + " is running : " + i);try {queue1.take();} catch (InterruptedException e) {e.printStackTrace();}}}}
- ArrayBlockingQueue使用
- 阻塞队列使用---ArrayBlockingQueue
- java ArrayBlockingQueue 使用示例
- ArrayBlockingQueue的使用
- ArrayBlockingQueue
- ArrayBlockingQueue
- ArrayBlockingQueue
- ArrayBlockingQueue
- ArrayBlockingQueue
- ArrayBlockingQueue
- ArrayBlockingQueue
- ArrayBlockingQueue
- ArrayBlockingQueue
- ArrayBlockingQueue
- 多线程之ArrayBlockingQueue的使用
- ArrayBlockingQueue和LinkedBlockingQueue的使用
- ArrayBlockingQueue和LinkedBlockingQueue的使用
- ArrayBlockingQueue源码分析及使用
- 1007
- LIB和DLL的区别与使用
- 吉哥系列故事——临时工计划
- Java MongoDB 学习
- java通配符的使用方法
- ArrayBlockingQueue使用
- UVA - 10163 Storage Keepers
- 图算法 具有负边值有向图的单源最短路径
- 使用grep来查找当前文件夹下边所有包含某个字符串的文件
- 修改RT5370网卡VID/PID
- mysql join的实现原理及优化思路
- 如何理解oracle 11g scan ip
- 文本编辑器代码分析
- SpannableString对象赋值为String 资源里面定义的字符串