The Blockingqueue<e> interface defines a queue that includes two additional functions. These two functions are: If an element is taken from an empty queue or an element is added to a full queue, a wait state is entered. The method in the Blockinqueue interface Pu (e) T and take () can make it into an infinite blocking state, which can be used to achieve producer and consumer problems, relatively simple.
The code is as follows:
Package Com.lk.b;import Java.util.random;import Java.util.concurrent.blockingqueue;import Java.util.concurrent.linkedblockingqueue;public class Test5 {private blockingqueue<integer> queue = new Linkedblockingqueue<> (2);p Rivate class Producer implements runnable{@Overridepublic void Run () {//TODO Auto-generated method Stubfor (int i=0;i<5;i++) {int b = new Random (). Nextint (255); try {queue.put (b); System.out.println ("Add +b+ to queue" \ t queue has "+queue.size () +" elements ");} catch (Interruptedexception e) {//TODO auto-generated catch Blocke.printstacktrace ();}}} Private class Consumer implements runnable{@Overridepublic void Run () {try {thread.sleep];} catch ( Interruptedexception E1) {//TODO auto-generated catch Blocke1.printstacktrace ();} TODO auto-generated method stubfor (int i=0;i<5;i++) {int b = 0;try {b=queue.take (); System.out.println ("Remove from queue" +b+ "\ t queue has" +queue.size () + "elements");} catch (Interruptedexception e) {//TODO auto-generated catch Blocke.printstacktrace ();}}} public static void Main (string[] args) {Test5 test5 = new Test5 (); Producer Producer = Test5.new Producer (); Consumer Consumer = Test5.new Consumer (); new Thread (producer). Start (); new Thread (Consumer). Start ();}
Operation Result:
/* Add 127 queues to the queue with 1 elements into the queue 113 queues with 2 elements removed from the queue 127 elements in the queue are added to the queues with 1 elements removed from the queue 2 in the queue with 113 elements removed from the queue There are 0 elements in the queue that are added to the queue 212 queues have 1 elements removed from the queue 212 queues have 0 elements into the queue 243 elements are removed from the queue 1 have 243 elements in the queue */
Using blocking queues to implement producer and consumer issues