import java.util.LinkedList;import java.util.concurrent.TimeUnit;import java.util.concurrent.atomic.AtomicInteger;public class MyQueue { //1 需要一個承裝元素的集合 PRivate LinkedList<Object> list = new LinkedList<Object>(); //2 需要一個計數器 private AtomicInteger count = new AtomicInteger(0); //3 需要制定上限和下限 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里面有空間再繼續. 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); } } //take: 取走BlockingQueue里排在首位的對象,若BlockingQueue為空,阻斷進入等待狀態直到BlockingQueue有新的數據被加入. 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 計數器遞減 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(); try { TimeUnit.SECONDS.sleep(3); } catch (InterruptedException e) { e.printStackTrace(); } 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"); t2.start(); } }
新聞熱點
疑難解答