8月的笔记
import java.util.LinkedList;
import java.util.concurrent.atomic.AtomicInteger;
public class MyBlockQueue {
//裝載元素的集合
private final LinkedList<Object> list = new LinkedList<Object>();
//計數器
private final AtomicInteger count = new AtomicInteger(0);
//隊列的大小,上下限制
private final int minSize = 0;
private final int maxSize;
public MyBlockQueue(int maxSize){
this.maxSize = maxSize;
}
private final Object lock = new Object();
//put(Object) 入隊操作,阻塞加鎖;若隊列已滿,鎖一直等待,有空位才能入隊
public void put(Object element){
synchronized (lock) {
if (count.get() == this.maxSize) {
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//入隊
list.add(element);
//計數
count.incrementAndGet();
System.out.println("新加入元素: " + element);
//通知消費者消費
lock.notify();
}
}
//take(Object) 出隊操作,阻塞加鎖;若隊列空,鎖等待,有元素才能出隊
public Object take() {
Object take = null;
synchronized (lock) {
if (count.get() == this.minSize) {
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//出隊
take = list.removeFirst();
//計數
count.decrementAndGet();
System.out.println("移除元素");
//通知生產者放元素
lock.notify();
}
return take;
}
public int getSize(){
return this.count.get();
}
}
同樣,我們可以使用ReentranLock,並配合try…finally語句塊來實現