public class Fillqueuethread extends Thread {private queue queue;public Fillqueuethread (queue queue) {this.queue = queue;} @Overridepublic void Run () {while (true) {try {Boolean added = Queue.offer (Uuid.randomuuid (). toString ()); if (added) { System.out.println (Thread.CurrentThread (). GetName () + "Add 1 element"); Else{system.out.println (Thread.CurrentThread (). GetName () + "is blocked, wait");//this.wait//no to need wait }thread.sleep (100);} catch (Interruptedexception e) {//TODO auto-generated catch Blocke.printstacktrace ();}}}
public class Pollqueuethread extends Thread {private queue queue;public Pollqueuethread (queue queue) {this.queue = queue;} @Overridepublic void Run () {while (true) {try {Object el = Queue.poll (); if (null = = EL) {System.out.println ( Thread.CurrentThread (). GetName () + "is blocked, wait");//this.wait (); No need to invoked wait}else{system.out.println (Thread.CurrentThread (). GetName () + "Pool 1 element");} Thread.Sleep (50);} catch (Interruptedexception e) {//TODO auto-generated catch Blocke.printstacktrace ();}}}
public class Monitorqueuethread extends Thread {private Queue queue;public monitorqueuethread (queue queue) {This.queue = Q Ueue;} @Overridepublic void Run () {while (true) {System.err.println ("Queue size:" +queue.size ()); try {thread.sleep (500);} catch (Interruptedexception e) {e.printstacktrace ();}}}}
public class Helloqueue {public static void main (string[] args) {//arrayblockingqueue<string> queue = new Arrayblock Ingqueue<string> (500,true); linkedblockingqueue<string> queue = new linkedblockingqueue<string> (+), int threadfillnumber = 10;int Threadpollnumber = 3;for (int i=0; i<threadfillnumber; i++) {fillqueuethread th = new Fillqueuethread (queue); Th.start ( );} for (int i=0; i<threadpollnumber; i++) {pollqueuethread th = new Pollqueuethread (queue); Th.start ();} Monitorqueuethread monitor = new Monitorqueuethread (queue); Monitor.start ();}}