用 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();
}
}