package com.snake;
import java.util.LinkedList;
import java.util.concurrent.atomic.AtomicInteger;
/**
* 模拟阻塞队列Queue wait(),notify()
* 创建日期 :2016年5月10日
* @author jiangjianbin
*
*/
public class MyBlockQueue_Wait_Notify {
//1 需要一个承装元素的集合
private final LinkedList<Object> list = new LinkedList<Object>();
//2 需要一个计数器
private final AtomicInteger count = new AtomicInteger(0);
//3 需要制定上限和下限
private final int maxSize;
private final int minSize = 0;
//4初始化一个对象 用于加锁
private final Object lock = new Object();
//5 构造方法
public MyBlockQueue_Wait_Notify (int maxSize){
this.maxSize = maxSize;
}
//put(anObject): 把anObject加到BlockingQueue里,如果BlockQueue没有空间,则调用此方法的线程被阻断,直到BlockingQueue里面有空间再继续.
public void put(Object obj) {
synchronized(lock){
while(count.get() == maxSize){
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//1 加入元素
list.add(obj);
//2 计数器累加
count.incrementAndGet();
//3 通知另外一个线程(唤醒)
System.out.println(" 元素 " + obj + " 被添加 ");
lock.notify();
}
}
//take: 取走BlockingQueue里排在首位的对象,若BlockingQueue为空,阻断进入等待状态直到BlockingQueue有新的数据被加入.
public Object take(){
Object temp = null;
synchronized (lock) {
while(count.get() == minSize){
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//1 做移除元素操作
temp = list.removeFirst();
//2 计数器递减
count.decrementAndGet();
//3 唤醒另外一个线程
lock.notify();
System.out.println(" 元素 " + temp + " 被消费 ");
lock.notify();
}
return temp;
}
public int size(){
return count.get();
}
public static void main(String[] args) throws Exception {
final MyBlockQueue_Wait_Notify m = new MyBlockQueue_Wait_Notify(5);
m.put("a");
m.put("b");
m.put("c");
m.put("d");
m.put("e");
System.out.println("当前元素个数:" + m.size());
Thread t1 = new Thread(new Runnable() {
public void run() {
m.put("h");
m.put("i");
}
}, "t1");
Thread t2 = new Thread(new Runnable() {
public void run() {
try {
Thread.sleep(1000);
Object t1 = m.take();
Thread.sleep(1000);
Object t2 = m.take();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}, "t2");
t1.start();
Thread.sleep(1000);
t2.start();
}
}