1. Create Queue.java
public class Queue {private linkedlist<object> list = new linkedlist<object> ();p rivate final int minSize = 0 ;;p rivate Final int maxSize;p rivate atomicinteger count = new Atomicinteger (0);p ublic Queue (int size) {this.maxsize = Si Ze;} Private Final Object lock = new Object ();p ublic void put (Object o) {synchronized (lock) {while (size () = = This.maxsize) {try { Lock.wait ();} catch (Interruptedexception e) {e.printstacktrace ();}} List.add (o);//Counter increased count.incrementandget ();//Notification Wake-up lock.notify ();}} private int size () {return count.get ();} Public Object Take () {object res = NULL, synchronized (lock) {while (size () = = This.minsize) {try {lock.wait ();} catch (Interr Uptedexception e) {e.printstacktrace ();}} res = List.removefirst ();//Counter minus 1count.decrementandget (); Lock.notify ();} return res;} public static void Main (string[] args) {final queue MQ = new Queue (3), Mq.put ("a"), Mq.put ("B"), Mq.put ("C"), New Thread (new Runnable () {@Overridepublic void run () {mq.put ("G"); System.out.println ("Put1 SeccesefUL "); Mq.put (" F "); System.out.println ("Put2 secceseful");}). Start (); New Thread (New Runnable () {@Overridepublic void run () {System.out.println ("Take value =" +mq.take ())}). Start ();}}
The results of the operation are as follows:
Take value = Aput1 secceseful
When the first put is executed, the thread is blocked because the queue capacity is full. After another thread has taken, the blocked thread continues to execute the put success.
Java Multithreading implements simple queues