多线程之ArrayBlockingQueue的使用

阻塞队列ArrayBlockingQueue


package com.zwy.myThread;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/*模拟是一个放入数据一个取数据的过程,因为ArrayBlockingQueue是一个阻塞的队列
 * ,当放入数据时候 ,队列已经满了队列会阻塞,
 * 当取数据时候队列为空时候,队列会阻塞,这样就可以很好的模拟一个生产者消费者的问题了.
 * 可以调整sleep的时间来查看队满,跟队空的情况
 * */
public class BlockingQueueTest {
	public static void main(String[] args) {
		/*声明阻塞队列*/
		final ArrayBlockingQueue queue = new ArrayBlockingQueue(3);
		ExecutorService service = Executors.newCachedThreadPool();
		for(int i = 0 ; i < 2; i++){
			Runnable run = new Runnable(){
				public void run(){
					while(true){
							try{
								Thread.currentThread().sleep(1000);
								System.out.println(Thread.currentThread().getName()+":is ready to put data");
								/*放入数据 ,生产线程产生产品*/
								queue.put(1);
								System.out.println(Thread.currentThread().getName()+"放入数据之后:队列长度为"+queue.size());
						}catch(Exception e){
							e.printStackTrace();
						}
					}
				}
			};		
			service.execute(run);
		}
			service.execute(new Runnable(){
				public void run(){
					while(true){
							try{
								Thread.currentThread().sleep(1000);
								System.out.println(Thread.currentThread().getName()+":is ready to get data");
								/*取入数据 ,生产线程消费产品*/
								int i = (Integer) queue.take();
								System.out.println(Thread.currentThread().getName()+":取出数据:"+i);
								System.out.println(Thread.currentThread().getName()+"取出数据之后:队列长度为"+queue.size());
						}catch(Exception e){
							e.printStackTrace();
						}
					}
				}
			});
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值