JAVA linkedblockingqueue blocking Queues __java

Source: Internet
Author: User

In Java multi-threaded applications, queues are used very highly, and the preferred data structure for most production consumption models is queues. Java-provided thread-safe queues can be divided into blocking and non-blocking, where the typical example of blocking queues is blockingqueue, and a typical example of non-blocking queues is concurrentlinkedqueue. In practical application, the blocking queue or non-blocking queue should be chosen according to the actual needs.
Note: What is called thread safety. This first has to be clear. Thread safety means that multithreading accesses the same code without creating an indeterminate result.
linkedblockingqueue
because the Linkedblockingqueue implementation is thread-safe, it implements advanced first-out features, and is the preferred producer consumer The
Linkedblockingqueue can specify a capacity, or it can be unspecified or unspecified, by default the maximum is Integer.max_value, which is mainly used to put and take methods. 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 brought 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 implementation producer/consumer model * * @author Lin Yi-chin * @version 1.0 2013-7-25 pm 05:23:11 */publicclass BlockingQueueTest2 {/ * * * Definition of apple basket * */publicclass Basket {//basket, can hold 3 apples blockingqueue<string>

        Basket = new linkedblockingqueue<string> (3);
            produce apples, put in baskets publicvoid produce () throws Interruptedexception {//Put method into an apple, if basket full, wait until the basket have position
        Basket.put ("an apple"); //Consume Apple, take the public String from the basket consume () throws Interruptedexception {//Take method remove an apple, if basket is empty, wait until BAS
        Ket have 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;
                    Publicvoid run () {try {(true)} {//produce 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;
                    Publicvoid run () {try {while (true) {//consume 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"); 

        }} publicstaticvoid 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 (); }

}

The

concurrentlinkedqueue
Concurrentlinkedqueue is a security implementation of the queue. The elements in the queue are sorted by FIFO principle. The CAS operation is used to ensure the consistency of the elements. The
Linkedblockingqueue is a thread-safe blocking queue that implements the Blockingqueue interface, The Blockingqueue interface inherits from the Java.util.Queue interface and adds take and put methods based on this interface, which is exactly the blocking version of the queue operation.

Package cn.thread;
Import Java.util.concurrent.ConcurrentLinkedQueue;
Import Java.util.concurrent.CountDownLatch;
Import Java.util.concurrent.ExecutorService;

Import java.util.concurrent.Executors; Publicclass concurrentlinkedqueuetest {privatestatic concurrentlinkedqueue<integer> queue = new ConcurrentLinke
    Dqueue<integer> (); Privatestaticint count = 2; Number of threads//countdownlatch, a synchronization helper class, allows one or more threads to wait all the time before completing a set of operations that are being performed in another thread.

    Privatestatic Countdownlatch latch = new Countdownlatch (count);
        Publicstaticvoid Main (string[] args) throws Interruptedexception {Long Timestart = System.currenttimemillis ();
        Executorservice es = Executors.newfixedthreadpool (4);
        Concurrentlinkedqueuetest.offer ();
        for (int i = 0; i < count; i++) {Es.submit (New Poll ()); } latch.await (); Causes the main thread (main) to block until Latch.countdown () is zero to continue executing System.out.println ("Cost time" + (System.currenttimemillis ()-Timestar
        T) + "MS");Es.shutdown (); /** * Production */publicstaticvoid offer () {for (int i = 0; i < 100000; i++) {Queue.off
        ER (i); }/** * Consumption * * @author Lin Yi-chin * @version 1.0 2013-7-25 pm 05:32:56 */staticclass Poll I
                Mplements Runnable {publicvoid run () {//while (Queue.size () >0) {while (!queue.isempty ()) {
            System.out.println (Queue.poll ());
        } latch.countdown (); }
    }
}

Run Result:
Costtime 2360ms
Use while (Queue.size () >0)
Run Result:
Cost time 46422ms
The result was so different that I looked at the concur Rentlinkedqueue API originally. Size () is to iterate through the collection, no wonder so slow, so try to avoid using size to switch to IsEmpty ().
summed up, in the unit lack of performance testing, the requirements of their own programming more stringent, especially in the production environment should be cautious.

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.