1.LinkedBlockingQueue
/** * Use blocking synchronous queue LinkedBlockingQueue complete producer-consumer model * Use a scene more. */ public class T05_LinkedBlockingQueue { public static void main(String[] args) { BlockingQueue<String> queue = new LinkedBlockingQueue<>(); // start producer thread production of new new the Thread (() -> { for ( int J = 0 ; J < 100 ; J ++ ) { the try {
// Ruoguo container is full, it will wait here, in a spare container insert data queue.put ( " AAA " + J); // PUT method, additive elements to the container, if the container is full, it will block waiting } the catch (InterruptedException E) { e.printStackTrace (); } } }, "p").start(); try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace (); } // enable consumers to consume threads for ( int i = 0 ; i < 5 ; i ++ ) { new new the Thread (() -> { the while ( to true ) { the try { The System. OUT .println (Thread.currentThread () getName () +. " : " + Queue.take ()); // get the data from the queue, if empty, it will block waiting } the catch (InterruptedException E) { e.printStackTrace (); } } }, "c" + i).start(); } } }
2.ArrayBlockingQueue
/** * Use blocking synchronous bounded queue ArrayBlockingQueue complete producer-consumer model */ public class T06_ArrayBlockingQueue { public static void main(String[] args) throws InterruptedException { BlockingQueue queue = new ArrayBlockingQueue<>(10); for (int i = 0; i < 10; i++) { queue.put("a" + i); }
// PUT then in the case of a container full of waiting // queue.put ( "A11"); // will block // queue.add ( "A11"); // throws an exception // System. out.println (Queue.offer ( "A11")); // returns false System. OUT .println (Queue.offer ( " A11 " , 1 , TimeUnit.SECONDS)); // waits 1s, returns false, If there is a free return within 1s, then add success to true } }