线程之间通信2

用 wait/notify模拟实现一个 BlockingQueue

 

public class MyQueue {

	//承装元素的集合
	private final LinkedList<Object> list = new LinkedList<Object>();
	
	//计算器
	private AtomicInteger count = new AtomicInteger(0);
	
	private final int minSize = 0;
	
	private final int maxSize;
	
	public MyQueue(int size) {
		this.maxSize = size;
	}

	// 初始化一个锁对象 
	
	private final Object lock = new Object();
	
	public void put(Object obj){
		synchronized (lock) {
			while (count.get()==this.maxSize) {
				try {
					lock.wait();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			//1.加入元素
			list.add(obj);
			//2.计数器累加
			count.incrementAndGet();
			//3.通知另外的线程
			lock.notify();
			System.out.println(" 新加入的元素:"+obj);
		}
	}
	
	
	public Object take(){
		Object ret = null;
		synchronized (lock) {
			while (count.get()==this.minSize) {
				try {
					lock.wait();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			ret = list.removeFirst();
			count.decrementAndGet();
			lock.notify();
		}
		return ret;
	}
	
	
	public int getSize(){
		return this.count.get();
	}
	
	
	public static void main(String[] args) {
		final MyQueue queue = new MyQueue(5);
		queue.put("1");
		queue.put("2");
		queue.put("3");
		queue.put("4");
		queue.put("5");
		
		System.out.println("当前 queue 长度:"+queue.getSize());
		
		
		Thread t1 = new Thread(new Runnable() {
			
			@Override
			public void run() {
				queue.put("a");
				queue.put("b");
			}
		},"t1");
		
		t1.start();
		
		Thread t2 = new Thread(new Runnable() {
			@Override
			public void run() {
				System.out.println("t2 take:" +queue.take());
				System.out.println("t2 take:" +queue.take());
			}
		},"t2");
		
		try {
			TimeUnit.SECONDS.sleep(2);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		
		t2.start();
	}
	
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值