BlockingQueue: as the name implies, first it is a queue, and supports blocking mechanism, blocking putting and getting data. We need to implement two methods, put and take, under LinkedBlockingQueue
put(anObject): add an object to BlockingQueue. If BlockingQueue has no space, the thread calling this method will be blocked until there is space in BlockingQueue.
Take: take away the first object in BlockingQueue. If BlockingQueue is empty, block entering the waiting state until new data is added to BlockingQueue.
public class MyQueue { // 1 A set of mounting elements is required private LinkedList<Object> list = new LinkedList<Object>(); // 2 A counter is required private AtomicInteger count = new AtomicInteger(0); // 3 Upper and lower limits need to be established private final int minSize = 0; private final int maxSize; // 4 Construction method public MyQueue(int size) { this.maxSize = size; } // 5 Initializing an object for locking private final Object lock = new Object(); // put(anObject): // hold anObject Add to BlockingQueue in,If BlockQueue no space,The thread calling this method is blocked until BlockingQueue There's room to move on. public void put(Object obj) { synchronized (lock) { while (count.get() == this.maxSize) { try { lock.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } // 1 Adding elements list.add(obj); // 2 Counter accumulation count.incrementAndGet(); // 3 Notify another thread (wake up) lock.notify(); System.out.println("The newly added element is:" + obj); } } // take: // Take away BlockingQueue Top of the list,if BlockingQueue Empty,Block to wait until BlockingQueue New data is added. public Object take() { Object ret = null; synchronized (lock) { while (count.get() == this.minSize) { try { lock.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } // 1 Remove element ret = list.removeFirst(); // 2 Counter decrement count.decrementAndGet(); // 3 Wake up another thread 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("Length of current container:" + 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("Removed elements are:" + o1); Object o2 = mq.take(); System.out.println("Removed elements are:" + o2); } }, "t2"); try { TimeUnit.SECONDS.sleep(2); } catch (InterruptedException e) { e.printStackTrace(); } t2.start(); } }