import java.util.LinkedList;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
public class MyQueue {
private LinkedList<Object> list = new LinkedList<Object>();
//原子計數(shù)器
private AtomicInteger count = new AtomicInteger(0);
//需要制定上限和下限
private final int minSize = 0;
private final int maxSize;
//4構造方法
public MyQueue(int size) {
this.maxSize = size;
}
//5初始化一個對象 用于加鎖
private final Object lock = new Object();
//put(anObject):把anObject加到BlockingQueue里,如果blockqueue沒有空間,
//則調用方法的線程被阻斷,直到blockingqueue里面有空間再繼續(xù)。
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.計數(shù)器累加
count.incrementAndGet();
//3.通知另外一個線程
lock.notify();
System.out.println("新加入的元素為:"+obj);
}
}
/**
* take: 取走blockingqueue里排在首位的對象,若blockingqueue為空
* 阻斷進入等待狀態(tài)直到blockqueue有新的數(shù)據(jù)加入
* @return
*/
public Object take() {
Object ret = null;
synchronized (lock) {
while(count.get() == this.minSize) {
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//1 做移除元素操作
ret = list.removeFirst();
//2 計數(shù)器遞減
count.decrementAndGet();
//3 喚醒另外一個線程
lock.notify();
}
return ret;
}
public int getSize() {
return this.count.get();
}
public static void main(String[] args) {
final MyQueue mq = new MyQueue(5);
mq.put("a");
mq.put("b");
mq.put("c");
mq.put("d");
mq.put("e");
System.out.println("當前容器的長度:"+mq.getSize());
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
mq.put("f");
mq.put("g");
}
},"t1");
t1.start();
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
Object o1 = mq.take();
System.out.println("移除的元素為:"+o1);
Object o2 = mq.take();
System.out.println("移除的元素為:"+o2);
}
},"t2");
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
t2.start();
}
}
用wait和notify方式模擬queue
最后編輯于 :
?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。