ArrayBlockingQueue使用

【参考文章:】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();
			}
		}	
	}

}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值