Simulate Queue (wait/notify), queuenoworkflow
BlockingQueue: As the name implies, BlockingQueue is a queue and supports blocking mechanisms to block incoming and outgoing data. We need to implement the put and take methods below the LinkedBlockingQueue. put (anObject): Add anObject to BlockingQueue. If BlockingQueue has no space, the thread that calls this method is blocked until there is space in BlockingQueue. Take: removes the first object in BlockingQueue. If BlockingQueue is empty, it is blocked and enters the waiting state until new data is added to BlockingQueue.
Public class MyQueue {// 1 requires a collection of mounted elements, private upload list <Object> list = new upload list <Object> (); // 2 requires a counter private AtomicInteger count = new AtomicInteger (0); // 3 requires the upper and lower limits private final int minSize = 0; private final int maxSize; // 4 constructor public MyQueue (int size) {this. maxSize = size;} // 5 Initialize an Object to lock private final Object lock = new Object (); // put (anObject): // Add anObject to BlockingQueue, if BlockQueue has no space, the thread that calls this method is blocked until there is space in BlockingQueue. public void put (Object obj) {synchronized (lock) {while (count. get () = this. maxSize) {try {lock. wait ();} catch (InterruptedException e) {e. printStackTrace () ;}// 1 is added to the element list. add (obj); // 2 the counter accumulates count. incrementAndGet (); // 3 notify another thread (wake up) lock. using Y (); System. out. println ("the newly added element is:" + obj) ;}// take: // removes the first object in BlockingQueue. If BlockingQueue is empty, the block enters the waiting state until new data is added to BlockingQueue. public Object take () {Object ret = null; synchronized (lock) {while (count. get () = this. minSize) {try {lock. wait ();} catch (InterruptedException e) {e. printStackTrace () ;}// 1. Perform the delete element operation ret = list. removeFirst (); // 2 the counter decreases by count. decrementAndGet (); // 3 wake up another thread lock. required y ();} 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 ("current container length:" + 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 element:" + o1); Object o2 = mq. take (); System. out. println ("removed element:" + o2) ;}}, "t2"); try {TimeUnit. SECONDS. sleep (2);} catch (InterruptedException e) {e. printStackTrace () ;}t2.start ();}}