简单队列的实现
下面是自己通過linkedList實現的一個簡單隊列
public class MyQueue {//1、需要一個承載元素的集合privakte 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;}//初始化一個對象用于加鎖private final Object lock = new Object();//put(anObject): 把anObject加到BlockingQueue里,如果BlockQueue沒有空間,則調用此方法的線程被阻斷,直到BlockingQueue里面有空間再繼續public void put(Object object){synchronized (lock){while (count.get()==this.maxSize){try {lock.wait();} catch (InterruptedException e) {e.printStackTrace();}}//1、加入元素list.add(object);//2、計數器累加count.incrementAndGet();//3、通知另一個線程(喚醒)lock.notify();System.out.println("新加入的元素為:"+object);}}//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();}}ret = list.removeFirst();count.decrementAndGet();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() {@Overridepublic void run() {mq.put("f");mq.put("g");}},"t1");t1.start();Thread t2 = new Thread(new Runnable() {@Overridepublic 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();} } 復制代碼轉載于:https://juejin.im/post/5abd8da45188255caf064e4a
總結
- 上一篇: 云计算是数据分析的最佳场所吗?
- 下一篇: Django+xadmin打造在线教育平