Using Java's blockingqueue to implement producer-consumer

Source: Internet
Author: User

Blockingqueue is also the main tool for controlling thread synchronization under Java.util.concurrent.

Blockingqueue has four specific implementation classes, depending on the needs, choose different implementation classes
1, Arrayblockingqueue: a bounded block queue supported by an array, specifying the size of the Blockingqueue, its constructor must take an int parameter to indicate its size. The objects it contains are sorted in FIFO (first in, first out) order.


2, Linkedblockingqueue: The size of the variable blockingqueue, if its constructor with a specified size parameters, the resulting blockingqueue has a size limit, if not with the size of parameters, The size of the generated blockingqueue is determined by Integer.max_value. The objects it contains are sorted in FIFO (first in, first out) order.


3. Priorityblockingqueue: Similar to Linkedblockqueue, but the sort of objects it contains is not FIFO, but is determined by the natural sort order of the object or the comparator of the constructor.


4, Synchronousqueue: Special Blockingqueue, the operation of its must be put and take alternating completion.

Linkedblockingqueue can specify the capacity, or can not specify, if not specified, the default maximum is Integer.max_value, which is mainly used in the put and take method, the put method is blocked when the queue is full until a queue member is consumed, The Take method blocks when the queue is empty until a queue member is put in.

Sample code for producer consumers:

Producers:

Java code
  1. import java.util.concurrent.BlockingQueue;
  2. Public class Producer implements Runnable {
  3. Blockingqueue<string> queue;
  4. Public Producer (blockingqueue<string> queue) {
  5. this. Queue = queue;
  6. }
  7. @Override
  8. Public void Run () {
  9. Try {
  10. String temp = "A product, production line:"
  11. + Thread.CurrentThread (). GetName ();
  12. System.out.println ("I have made a product:"
  13. + Thread.CurrentThread (). GetName ());
  14. Queue.put (temp); //If the queue is full, it will block the current thread
  15. } catch (Interruptedexception e) {
  16. E.printstacktrace ();
  17. }
  18. }
  19. }
Import Java.util.concurrent.blockingqueue;public class Producer implements Runnable {blockingqueue<string> Queue;public Producer (blockingqueue<string> queue) {this.queue = queue;} @Overridepublic void Run () {try {String temp = "A product, Production line:" + thread.currentthread (). GetName (); System.out.println ("I have made a product:" + thread.currentthread (). GetName ()); Queue.put (temp);//If the queue is full, it blocks the current thread} catch (Interruptedexception e) {e.printstacktrace ();}}}

Consumers:

Java code
  1. import java.util.concurrent.BlockingQueue;
  2. Public class Consumer implements runnable{
  3. Blockingqueue<string> queue;
  4. Public Consumer (blockingqueue<string> queue) {
  5. this. Queue = queue;
  6. }
  7. @Override
  8. Public void Run () {
  9. Try {
  10. String temp = Queue.take (); //If the queue is empty, the current thread is blocked
  11. SYSTEM.OUT.PRINTLN (temp);
  12. } catch (Interruptedexception e) {
  13. E.printstacktrace ();
  14. }
  15. }
  16. }
Import Java.util.concurrent.blockingqueue;public class Consumer implements Runnable{blockingqueue<string> Queue;public Consumer (blockingqueue<string> queue) {this.queue = queue;} @Overridepublic void Run () {try {String temp = Queue.take ();//If the queue is empty, it blocks the current thread System.out.println (temp);} catch ( Interruptedexception e) {e.printstacktrace ();}}}

Test class:

Java code
  1. import java.util.concurrent.ArrayBlockingQueue;
  2. import java.util.concurrent.BlockingQueue;
  3. import java.util.concurrent.LinkedBlockingQueue;
  4. Public class TEST3 {
  5. Public Static void Main (string[] args) {
  6. blockingqueue<string> queue = new linkedblockingqueue<string> (2);
  7. //blockingqueue<string> queue = new linkedblockingqueue<string> ();
  8. //Not set, linkedblockingqueue default size is Integer.max_value
  9. //blockingqueue<string> queue = new arrayblockingqueue<string> (2);
  10. Consumer Consumer = new Consumer (queue);
  11. Producer Producer = new Producer (queue);
  12. for (int i = 0; i < 5; i++) {
  13. New Thread (producer, "producer" + (i + 1)). Start ();
  14. New Thread (Consumer, "consumer" + (i + 1)). Start ();
  15. }
  16. }
  17. }
Import Java.util.concurrent.arrayblockingqueue;import Java.util.concurrent.blockingqueue;import Java.util.concurrent.linkedblockingqueue;public class Test3 {public static void main (string[] args) {blockingqueue< string> queue = new linkedblockingqueue<string> (2);//blockingqueue<string> queue = new Linkedblockingqueue<string> ();//If not set, linkedblockingqueue default size is integer.max_value//blockingqueue<string > queue = new arrayblockingqueue<string> (2); Consumer Consumer = new Consumer (queue); Producer Producer = new Producer (queue), for (int i = 0; i < 5; i++) {New Thread (Producer, "Producer" + (i + 1)). Start () ; New Thread (Consumer, "consumer" + (i + 1)). Start ();}}

Printing results:

Text Code
    1. i have made a product:producer1  
    2. i have made a& nbsp;product:producer2  
    3. a product,  production line:producer1  
    4. A  product,  production line:producer2  
    5. i have made a product:producer3   
    6. a product,  production line:producer3  
    7. i have made a  product:producer5  
    8. i have made a product:producer4  
    9. a product,  production line:producer5  
    10. a product,  production line:producer4  
I have made a product:producer1i has made a PRODUCT:PRODUCER2A product, production line: Producer1a product, production line: Producer2i has mad e a PRODUCT:PRODUCER3A product, production line: Producer3i has made a product:producer5i has made a PRODUCT:PRODUCER4A product, production line Process: producer5a product, production line: Producer4

Since the size of the queue is limited to 2, up to two products are added to the queue, and the order in which consumers take the product is in order of production, The reason is that both linkedblockingqueue and arrayblockingqueue are accessing elements in FIFO order.

Using Java's blockingqueue to implement producer-consumer

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.