Java Concurrency Programming (24)----(Juc collection) Arrayblockingqueue and Linkedblockingqueue Introduction __ Programming

Source: Internet
Author: User
Tags prepare sorts

In this section we take a look at the blocking queue (Blockingqueue), where the Blockingqueue interface defines a blocking FIFO queue in which each blockingqueue has a capacity Adding data to the blockingqueue when the capacity is full will block, and the fetch element operation blocks when the capacity is empty. First, let's look at Arrayblockingqueue and Linkedblockingqueue. Arrayblockingqueue

Arrayblockingqueue is a bounded blocking queue implemented with arrays. This queue sorts the elements according to the first-in first out (FIFO) principle. By default, visitors are not guaranteed a fair access queue, the so-called fair Access queue is the blocking of all producer threads or consumer threads, when the queue is available, you can access the queue in a blocking sequence, that is, the first blocked producer thread, you can first insert elements into the queue, first blocked consumer threads, You can get the elements from the queue first. Typically, the throughput is reduced to ensure fairness.

Let's see his constructor implementations:

The default is unjust, initially specifying the queue capacity public
arrayblockingqueue (int capacity) {This
       (capacity, false)
   ;

This construction method can set the fairness of the queue. Of course, if it's fair, it will have an impact on performance
///The fairness of the visitor is the public
arrayblockingqueue (int capacity, Boolean fair) {
       if (s) implemented using a reentrant lock ( Capacity <= 0)
           throw new IllegalArgumentException ();
       This.items = new Object[capacity];
       lock = new Reentrantlock (fair);
       Notempty = Lock.newcondition ();
       Notfull =  lock.newcondition ();
   }

Easy to use we look directly at an instance:

public class Producerconsumertest {public static void main (string[] args) {final blockingqueue<integer&gt ;

        Blockingqueue = new arrayblockingqueue<integer> (3);

        Executorservice service = Executors.newfixedthreadpool (10);
        for (int i = 0;i<4;i++) {service.execute (new Producerandconsumer (Blockingqueue));

    Class Producerandconsumer implements runnable{private Boolean flag = false;

    Private Integer j = 1;

    Private lock lock = new Reentrantlock ();

    Condition Pro_con = Lock.newcondition ();

    Condition Con_con = Lock.newcondition ();

    Private blockingqueue<integer> Blockingqueue;
    Public Producerandconsumer (blockingqueue<integer> blockingqueue) {this.blockingqueue= BlockingQueue;
            //Production public void put () {try {lock.lock ();
            while (flag) pro_con.await (); SYSTEM.OUT.PRINTLN ("Preparing to put data ...")
            "); Thread.Sleep (new Random (). Nextint (10) *100);
            Integer value = new Random (). Nextint (30);
            Blockingqueue.put (value);
            System.out.println (Thread.CurrentThread (). GetName () + "put in data" +value);
            Flag = true;
        Con_con.signal ();
        catch (Exception e) {e.printstacktrace ();
        } finally{Lock.unlock ();
            } public void get () {try {lock.lock ();
            while (!flag) con_con.await (); SYSTEM.OUT.PRINTLN ("Preparing to fetch data ...")
            ");
            Thread.Sleep (New Random (). Nextint (10) *1000);
            System.out.println (Thread.CurrentThread (). GetName () + "The data taken is" +blockingqueue.take ());
            Flag = false;
        Pro_con.signal ();
        catch (Exception e) {e.printstacktrace ();
        } finally{Lock.unlock (); @Override public void Run () {while (true) {if (j==1)) {put ();
            } else{get ();
        } j= (j+1)%2; }
    }
}

The output is:

Preparing to put data ...
preparing to put data ...
preparing to put data ...
preparing to put data ...
pool-1-thread-2   put in the    data
is ready to fetch data ...
pool-1-thread-3   put in Data    4
is preparing to fetch data ...
pool-1-thread-3   Data is
being prepared to put into the data ...
pool-1-thread-1   put the data one by one
is preparing to fetch data ...
pool-1-thread-4   put in the    data
is ready to fetch data ...
pool-1-thread-1   The data to be 4
is ready to put the data ...
pool-1-thread-2   The data that is being taken is ready to be
put into the data ...
pool-1-thread-3   put in the    data
is ready to fetch data ...
...
...
Linkedblockingqueue

Linkedblockingqueue is a bounded blocking queue implemented with a linked list. The default and maximum length for this queue is integer.max_value. This queue sorts the elements according to the FIFO principle.
Let's take a look at his constructor:

Public Linkedblockingqueue () {This
  (integer.max_value);  max_value=2147483647
 } public

linkedblockingqueue (int capacity) {
     if (capacity <= 0) throw new IllegalArgumentException ();
     This.capacity = capacity;
     last = head = new node<e> (null);
 }

Let's just take a look at an example:

public class Blockingqueuetest {/** * defines an apple basket/public static class Basket {//basket that can hold 3 apples
        Blockingqueue<string> basket = new arrayblockingqueue<string> (3);

        Blockingqueue<string> basket = new linkedblockingqueue<string> (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 {//Get method to remove an apple, if basket
        For empty, wait until basket have Apple return Basket.take (); }//test method public static void Testbasket () {//Create an Apple basket final basket basket = new Baske

        T ();

            Define Apple producer Class Producer implements Runnable {public String instance = "";
            Public Producer (String a) {instance = A; } public void Run() {try {while (true) {//production of Apple Syst
                        Em.out.println ("producer prepares to produce Apple:" + instance);
                        Basket.produce (); SYSTEM.OUT.PRINTLN ("!
                        Producer production of Apple finished: "+ instance";
                    Dormant 300ms Thread.Sleep (300);
        } catch (Interruptedexception ex) {}}//define Apple Consumer

            Class Consumer implements Runnable {public String instance = "";
            Public Consumer (String a) {instance = A; public void Run () {try {while (true) {//consumption Apple
                        Fruit System.out.println ("Consumer ready to consume Apple:" + instance);
                        Basket.consume (); SYSTEM.OUT.PRINTLN ("!
                        Consumer consumer Apple finished: "+ instance"; Hibernate 1000ms
                        Thread.Sleep (1000); } catch (Interruptedexception ex) {}}} Executorservice s
        Ervice = Executors.newcachedthreadpool ();
        Producer Producer = new Producer ("P1");
        Producer producer2 = new Producer ("P2");
        Consumer Consumer = new Consumer ("C1");
        Service.submit (producer);
        Service.submit (PRODUCER2);

        Service.submit (consumer);
        After the program runs 3s, all tasks stop try {thread.sleep (3000);
    catch (Interruptedexception e) {} service.shutdownnow ();
    public static void Main (string[] args) {blockingqueuetest.testbasket (); }
}

The output is:

Producers ready to produce apples: P1
Consumers are ready to consume Apple: C1
! Producers are producing apples: P1
producers are ready to produce apples: P2
! Consumer Apple finished: C1
! Producer Production Apple finished: P2
Producers ready to produce apples: P2
! Producers produce Apple finished: P2
producers ready to produce apples: P1
! Producers produce apples: P1 producers
prepare to produce apples: P2
producers prepare to produce apples: P1
Consumer ready to consume Apple: C1
! Consumer consumption Apple finished: C1
! Producer Production Apple finished: P2
producers ready to produce Apple: P2 consumers are
ready to consume the Apple: C1
! Consumer Apple finished: C1
! Producers to produce Apple finished: P1
producers ready to produce Apple: P1
consumer ready to consume Apple: C1
! Consumer Apple finished: C1
! Producer Production Apple finished: P2

process Finished with exit code 0

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.