java-thread-Use blocking queue (blockingqueue) to control thread communication

Source: Internet
Author: User

Blockingqueue is an interface that is also a sub-interface of the queue. Blockingqueue has a feature: When a producer thread attempts to place an element into the Blockingqueue, the thread is blocked if the queue is full, but if the queue is empty when the consumer thread tries to remove the element from the Blockingqueue The thread is blocked.

The two threads of a program can control the communication of threads well by alternately placing elements in blockingqueue and removing elements.

Blockingqueue provides the following two methods to support blocking:

put (E): attempts to place the EU element as blockingqueue, and if the element of the queue is full, the thread is blocked.

Take (): attempts to remove an element from the Blockingqueue's head, blocking the thread if the element of the queue is empty.

Blockingqueue inherits the queue interface, but can also use the methods in the queue interface, which can be grouped into the following three groups:

1, insert elements at the end of the queue, including Add (e), offer (e), put (e) method, when the queue is full, these three methods will throw an exception, return false, block the queue.

2. Delete the deleted element at the head of the queue. Including the Remove (), poll (), and take () methods, when the queue is empty, these three methods throw exceptions, return false, and block the queue.

3. Remove the element from the head of the queue without deleting it. The element () and peek () methods are included, and when the queue is empty, the two methods throw an exception and return false, respectively.

The Blockingqueue interface consists of the following 5 implementation classes:

1. Arrayblockingqueue: An array-based implementation of the Blockingqueue queue.

2, Linkedblockingqueue: The Blockingqueue queue based on the linked list implementation.

3, Priorityblockingqueue: It is not a categorization malleability blocking queue, when the queue calls remove (), poll (), take () and other methods to extract the elements, not to take out the longest time in the queue element, but the smallest element in the queue. It determines the size of the element to be naturally sorted according to the size of the element (implementing the comparable interface), or it can be customized using comparator.

4, Synchronousqueue: Synchronization queue. The storage and fetching operations on the queue must be performed alternately.

5, Delayqueue: It is a special blockingqueue, the bottom based on priorityblockingqueue implementation, however, the delayqueue requires that the set element to implement the delay interface (the interface has only a long Getdelay () method), Delayqueue is sorted based on the return value of the Getdalay () method of the collection element.

1 ImportJava.util.concurrent.ArrayBlockingQueue;2 ImportJava.util.concurrent.BlockingQueue;3  Public classblockingqueuetest{4      Public Static voidMain (string[] args)throwsexception{5         //Create a blockingqueue with a capacity of 16         7Blockingqueue<string> b=NewArrayblockingqueue<> (1);8         //start 3 producer Threads9         NewProducer (b). Start ();Ten         NewProducer (b). Start (); One         NewProducer (b). Start (); A         //Start a consumer thread -         NewConsumer (b). Start (); -          the     } - } - classProducerextendsthread{ -     PrivateBlockingqueue<string>b; +      -      PublicProducer (blockingqueue<string>b) { +          This. b=b; A          at     } -      Public synchronized voidrun () { -String [] str=Newstring[]{ -"Java", -"Struts", -"Spring" in         }; -          for(inti=0;i<9999999;i++){ toSystem.out.println (GetName () + "producer ready to produce collection elements!" "); +             Try{ -              theB.put (str[i%3]); *Sleep (1000); $                 //try to put the element, if the queue is full, the thread is blockedPanax Notoginseng                  -}Catch(Exception e) {System.out.println (e);} theSystem.out.println (GetName () + "production Complete:" +b); +         } A          the     } + } - classConsumerextendsthread{ $     PrivateBlockingqueue<string>b; $      PublicConsumer (blockingqueue<string>b) { -          This. b=b; -     } the      Public  synchronized  voidrun () { -     Wuyi          while(true){ theSystem.out.println (GetName () + "consumer ready to consume collection elements!" "); -             Try{ WuSleep (1000); -                 //attempt to remove element, if queue is empty, thread is blocked About B.take (); $}Catch(Exception e) {System.out.println (e);} -System.out.println (GetName () + "consumption finished:" +b); -         } -      A     } +}

java-thread-Use blocking queue (blockingqueue) to control thread communication

Related Article

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.