BlockingQueue的使用范围非常的广泛,比如线程池中的阻塞队列,阻塞的原因在于:
1.当队列的容量达到最大时,再加入元素就会处于阻塞状态,当有空位置时会自动加入
2.当队列的容量为最小时,取元素就会被阻塞,当容器中有元素时会自动取出。
这里使用wait/notify来模拟BlockingQueue中的put和take操作。
public class MyBlockingQueue {
//构造一个队列容器
private LinkedList<Object> list=new LinkedList<>();
//构造计数器
private AtomicInteger count=new AtomicInteger();
//容器大小
private final Integer minSize=0;
private final Integer maxSize;
public MyBlockingQueue(Integer maxSize) {
this.maxSize = maxSize;
}
public synchronized void put(Object obj) {
if(list.size()==maxSize){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
list.add(obj);
count.addAndGet(1);
this.notify();
}
public synchronized Object take() {
if(list.size()==minSize){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Object res=list.removeFirst();
count.decrementAndGet();
this.notify();
return res;
}
public void print(){
for (Object obj : list) {
System.out.println(obj);
}
}
public static void main(String[] args) {
MyBlockingQueue blockingQueue = new MyBlockingQueue(5);
blockingQueue.put(1);
blockingQueue.put(2);
blockingQueue.put(3);
blockingQueue.put(4);
blockingQueue.put(5);
new Thread(new Runnable() {
@Override
public void run() {
blockingQueue.put(6);
blockingQueue.put(7);
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
Integer num = (Integer)blockingQueue.take();
System.out.println("移除了元素: "+num);
Integer num2 = (Integer)blockingQueue.take();
System.out.println("移除了元素: "+num2);
}
}).start();
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("容器中现有元素为...");
blockingQueue.print();
}
}