BlockQueue producer consumer example

Detailed explanation of BlockingQueue


Blocking queue, as the name implies, is first of all a queue. There are two commonly used queues:         first-in, first-out (FIFO): the elements of the queue inserted first are also the first to exit the queue, similar to the function of queuing.         To some extent, this kind of queue also reflects a kind of fairness.    Last In, First Out (LIFO): Elements inserted later in the queue are first out of the queue, which prioritizes the most recent events. The core of the blocking queue is the producer and the consumer.         When there is no data in the queue, all threads on the consumer side will be automatically blocked (suspended) until data is put into the queue         and the queue is filled with data. All threads at the end are automatically blocked (suspended) until there is an empty position in the queue and the thread is automatically awakened. The core method of BlockingQueue:         put data:             offer(anObject): Indicates that if possible, add anObject to the BlockingQueue, that is, if the BlockingQueue can accommodate,  return true, otherwise return false. (This method does not block the thread currently executing the method )         offer(E o, long timeout, TimeUnit unit), you can set the waiting time, if the BlockingQueue cannot be added to the queue within the specified time , it will return a failure.         put(anObject): Add anObject to the BlockingQueue. If the BlockQueue has no space, the thread calling this method is blocked until there is space in the BlockingQueue to continue.
    









    






        Get data:
          poll(time): Take the object ranked first in the BlockingQueue. If you can't take it out immediately, you can wait for the time specified by the time parameter. If you can't take  it, return null;
          poll(long timeout, TimeUnit unit): From the BlockingQueue Take out an object at the head of the queue, and if there is data available in the queue within the specified time, the data in the queue will be returned immediately. Otherwise, if there is no data available after the time expires, return null.
          take(): Take the first object in the BlockingQueue. If the BlockingQueue is empty, block and enter the waiting state until new data is added to the BlockingQueue; 
          drainTo(): ​​Get all the available data objects from the BlockingQueue at one time (you can also Specify the number of acquired data), this method can improve the efficiency of acquiring data; it is not necessary to lock or release locks in batches multiple times.

 

Liezi:

 

                package test;  

  

                import java.util.Random;  

                import java.util.concurrent.BlockingQueue;  

                import java.util.concurrent.TimeUnit;  

                import java.util.concurrent.atomic.AtomicInteger;  

  

                public class Producer implements Runnable {  

  

                    private volatile boolean isRunning = true;  

                    private BlockingQueue queue;  

                    private static AtomicInteger count = new AtomicInteger();  

                    private static final int DEFAULT_RANGE_FOR_SLEEP = 1000;  

                      

                    public Producer(BlockingQueue queue){  

                        this.queue = queue;  

                    }  

                      

                    @Override  

                    public void run() {  

                        String data = null;  

                        Random r = new Random();  

                          

                        System.out.println("====Start producer====");  

                        try{  

                            while(isRunning){  

                                System.out.println("====Producing data====");  

                                Thread.sleep(r.nextInt(DEFAULT_RANGE_FOR_SLEEP));  

                                  

                                data = "data:" + count.incrementAndGet();  

                                if(!queue.offer(data, 2, TimeUnit.SECONDS)){  

                                    System.out.println("Failed to put data: "+data);  

                                    continue;  

                                }  

                                  

                                System.out.println("Put data: " + data + " into the queue...");  

                                  

                            }  

                        }catch(InterruptedException e){  

                            e.printStackTrace ();  

                            Thread.currentThread().interrupt();  

                        }finally{  

                            System.out.println("====Exit producer thread====");  

                        }  

                    }  

                      

                    public void stop(){  

                        isRunning = false;  

                    }  

                      

                }  

  

                package test;  

  

                import java.util.Random;  

                import java.util.concurrent.BlockingQueue;  

                import java.util.concurrent.TimeUnit;  

  

                public class Consumer implements Runnable{  

                      

                    private BlockingQueue<String> queue;  

                    private static final int DEFAULT_RANGE_FOR_SLEEP = 1000;  

                      

                    public Consumer(BlockingQueue<String> queue){  

                        this.queue = queue;  

                    }  

  

                    @Override  

                    public void run() {  

                        System.out.println("====Start consumer thread!====");  

                        Random r = new Random();  

                        boolean isRunning = true;  

                          

                        try{  

                            while(isRunning){  

                                System.out.println("====Get data from queue====");  

                                String data = queue.poll(2, TimeUnit.SECONDS);  

                                if(null != data){  

                                    System.out.println("Get data: "+data);  

                                    System.out.println("Consumption data: "+data);  

                                    Thread.sleep(r.nextInt(DEFAULT_RANGE_FOR_SLEEP));  

                                }else{  

                                    isRunning = false;  

                                }  

                            }  

                        }catch(InterruptedException e){  

                            e.printStackTrace ();  

                            Thread.currentThread().interrupt();  

                        }finally{  

                            System.out.println("====Exit consumer thread!====");  

                        }  

                    }  

                      

                }  

  

                package test;  

  

                import java.util.concurrent.BlockingQueue;  

                import java.util.concurrent.ExecutorService;  

                import java.util.concurrent.Executors;  

                import java.util.concurrent.LinkedBlockingQueue;  

  

  

                public class Test {  

  

                    public static void main(String[] args) throws InterruptedException {  

                        BlockingQueue<String> queue = new LinkedBlockingQueue<String>(10);  

                          

                        Producer producer1 = new Producer(queue);  

                        Producer producer2 = new Producer(queue);  

                        Producer producer3 = new Producer(queue);  

                        Consumer consumer = new Consumer(queue);  

                          

                        ExecutorService service = Executors.newCachedThreadPool();  

                        service.execute(producer1);  

                    service.execute(producer2);  

                    service.execute(producer3);  

                    service.execute(consumer);  

  

                    Thread.sleep(10 * 1000); //The producer executes 10m  

                    producer1.stop();  

                    producer2.stop();  

                    producer3.stop();  

                      

                    Thread.sleep(2000);  

                      

                    //Exit Executor  

                    service.shutdown();  

                    }  

                }  

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326411757&siteId=291194637