Thread sip blocking Queue __java in JAVA

Source: Internet
Author: User

Recently in the study of Java with the JDK and the contract, Java.util.concurrent, Discovery is very powerful, one of which is the work of many times the use of threading tool class Blockingqueue. During the actual development work and interview process, the use and understanding of the tool class is often examined.

1. What is a blocking queue. a blocking queue (Blockingqueue) is a queue that supports two additional operations. The two additional actions are that when the queue is empty, the thread that gets the element waits for the queue to become non-null. When the queue is full, the thread that stores the elements waits for the queue to be available. Blocking queues are often used by producers and consumers, and producers are threads that add elements to the queue, and consumers are the threads that take elements from the queue. A blocking queue is a container in which the producer stores elements, and the consumer takes only the elements from the container.

2. Detailed Blockingqueue


Blockingqueue will end up with four different situations, throwing exceptions, returning special values, blocking, timeouts, and the following table summarizes these methods:


Throw an exception Special value Blocking Timeout
Insert Add (E) Offer (e) Put (e) Offer (E, time, unit)
Removed from Remove () Poll () Take () Poll (time, unit)
Check Element () Peek () Not available Not available


Blockingqueue is an interface, like the following implementation class:

1. Arrayblockqueue: A bounded blocking queue supported by an array. This queue sorts the elements according to the FIFO (first-in first out) principle. The object you create must have an explicit size, like an array.

2. Linkedblockqueue: A blocking queue that can be changed in size. This queue sorts the elements according to the FIFO (first-in first out) principle. If you create an object with no explicit size, the default value is Integer.max_value. The throughput of a linked queue is typically higher than an array-based queue, but in most concurrent applications it has a low predictable performance.

3. Priorityblockingqueue: Similar to Linkedblockingqueue, but the sort of objects they contain are not FIFO, but are based on the natural sort order of the object or the order of comparator that the constructor takes.

4. Synchronousqueue: Synchronizing queues. The synchronization queue does not have any capacity, each insertion must wait for another thread to remove, and vice versa.


As the linkedblockingqueue implementation is thread-safe, the implementation of advanced first out and so on, is the preferred producer consumers , Linkedblockingqueue can specify the capacity, can not be specified, do not specify the words, The default maximum is Integer.max_value, where the put and take methods are used, and the put method blocks until a queue member is consumed when the queue is full, and the take method blocks when the queue is empty until a queue member is placed in.

Package cn.thread;
Import Java.util.concurrent.BlockingQueue;
Import Java.util.concurrent.ExecutorService;
Import java.util.concurrent.Executors;

Import Java.util.concurrent.LinkedBlockingQueue; /** * Multithreading simulation to achieve producer/consumer model */public class BlockingQueueTest2 {/** * * definition of apple basket */Pub Lic class Basket {//basket, able to hold 3 apple blockingqueue<string> basket = new LINKEDBLOCKINGQUEUE&LT;STRING&G

        t; (3);
            Produce Apple, put in basket public void produce () throws interruptedexception {//putting method into an apple, if basket full, wait until basket has position
        Basket.put ("an apple"); //Consume Apple, take the public String from the basket consume () throws Interruptedexception {//Take method to remove an apple, if Baske
        T is empty until basket has an apple (get and remove the head of this queue) return Basket.take ();
        }//define Apple Producer class Producer implements Runnable {private String instance;

        Private basket basket; Public Producer (String instance, basket baskET) {this.instance = instance;
        This.basket = basket;
                    The public void run () {try {) (true) {//is producing an apple
                    System.out.println ("producer prepares to produce Apple:" + instance);
                    Basket.produce ();
                    System.out.println ("! Producer produces Apple finished:" + instance);
                Dormant 300ms Thread.Sleep (300);
            } catch (Interruptedexception ex) {System.out.println ("Producer interrupted");
        }}//define Apple Consumer class Consumer implements Runnable {private String instance;

        Private basket basket;
            Public Consumer (String instance, basket basket) {this.instance = instance;
        This.basket = basket;
                    public void Run () {try {a while (true) {//consumer Apple SYSTEM.OUT.PRINTLN ("ConsumerReady to consume Apple: "+ instance";
                    System.out.println (Basket.consume ());
                    SYSTEM.OUT.PRINTLN ("! Consumer consumption Apple finished:" + instance);
                Dormant 1000ms thread.sleep (1000);
            } catch (Interruptedexception ex) {System.out.println ("Consumer interrupted"); }} public static void Main (string[] args) {BlockingQueueTest2 test = new BlockingQueueTest2 (

        );

        Build a basket of apples basket basket = test.new basket ();
        Executorservice service = Executors.newcachedthreadpool ();
        Producer Producer = Test.new Producer ("producer 001", basket);
        Producer producer2 = Test.new Producer ("producer 002", basket);
        Consumer Consumer = test.new Consumer ("Consumer 001", basket);
        Service.submit (producer);
        Service.submit (PRODUCER2);
        Service.submit (consumer);     After the program runs 5s, all tasks stop//try {//thread.sleep (1000 * 5);   catch (Interruptedexception e) {//E.printstacktrace ();//}//Service.shutdownnow (); }

}





Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.