The Java thread concurrency blockingqueue class USES the example

  • 2020-04-01 02:48:46
  • OfStack


If the BlockingQueue is full, any operation that tries to store something in the BlockingQueue will also be blocked into a wait state, and will not be awakened until there is a new space in the BlockingQueue to continue.

The main methods BlockingQueue provides are:

Add (anObject): add anObject to the BlockingQueue, if the BlockingQueue can hold the return true, otherwise throw an IllegalStateException exception.
Offer (anObject) : add anObject to the BlockingQueue, return true if the BlockingQueue can hold it, otherwise return false.
Put (anObject) : add anObject to the BlockingQueue. If the BlockingQueue has no space, the thread calling this method is blocked until there is a new space in the BlockingQueue.
Poll (time) : fetch the first object in the BlockingQueue, if not immediately fetch the time specified by the time parameter. Returns null when unreachable.
Take () : takes the first object in the BlockingQueue. If the BlockingQueue is empty, block it from entering the wait state until a new object is added to the BlockingQueue.

BlockingQueue has four specific implementations depending on your needs:

(1) ArrayBlockingQueue: BlockingQueue of specified size whose constructor must take an int to indicate its size. The contained objects are sorted in FIFO (first in, first out) order.
(2) LinkedBlockingQueue: BlockingQueue with variable size, if its constructor takes a specified size parameter, the generated BlockingQueue has a size limit,
Without the size argument, the size of the generated BlockingQueue is determined by integer.max_value. The contained objects are sorted in FIFO (first in, first out) order.
LinkedBlockingQueue and ArrayBlockingQueue, the data structures behind them are different,
The resulting data throughput of LinkedBlockingQueue is greater than that of ArrayBlockingQueue, but its performance is less predictable than that of ArrayBlockingQueue when the number of threads is large.
(3) PriorityBlockingQueue: similar to LinkedBlockingQueue, except that the sorting of the contained objects is not FIFO, but according to the natural sorting order of the objects or the Comparator with the constructor.
(4) SynchronousQueue: special BlockingQueue, whose operation must be done alternately by putting and taking.


package com.yao;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class BlockingQueueTest {
 
 public static class Basket{
  //The basket can hold 3 apples
  BlockingQueue<String> basket = new ArrayBlockingQueue<String>(3);

  //Produce apples and put them in baskets
  public void produce() throws InterruptedException{
   //The put method puts an apple in. If the basket is full, wait until the basket has a place
   basket.put("An apple");
  }
  //Consume the apples and take them out of the basket
  public String consume() throws InterruptedException{
   //If the basket is empty, wait until the basket has an apple
   String apple = basket.take();
   return apple;
  }

  public int getAppleNumber(){
   return basket.size();
  }

 }
 //The test method
 public static void testBasket() {
  //Create a basket of apples
  final Basket basket = new Basket();
  //Define the apple producer
  class Producer implements Runnable {
   public void run() {
    try {
     while (true) {
      //Production of apple
      System.out.println(" The producer prepares to produce apples: " 
        + System.currentTimeMillis());
      basket.produce();
      System.out.println(" The producer has finished producing apples: " 
        + System.currentTimeMillis());
      System.out.println(" Apple after production: "+basket.getAppleNumber()+" a ");
      //Dormancy 300 ms
      Thread.sleep(300);
     }
    } catch (InterruptedException ex) {
    }
   }
  }
  //Defining the apple consumer
  class Consumer implements Runnable {
   public void run() {
    try {
     while (true) {
      //Consumption of apple
      System.out.println(" Consumers ready to consume apple: " 
        + System.currentTimeMillis());
      basket.consume();
      System.out.println(" Consumers finish consuming apple: " 
        + System.currentTimeMillis());
      System.out.println(" After consumption of apples: "+basket.getAppleNumber()+" a ");
      //Dormancy 1000 ms
      Thread.sleep(1000);
     }
    } catch (InterruptedException ex) {
    }
   }
  }

  ExecutorService service = Executors.newCachedThreadPool();
  Producer producer = new Producer();
  Consumer consumer = new Consumer();
  service.submit(producer);
  service.submit(consumer);
  //After the program runs for 10s, all tasks stop
  try {
   Thread.sleep(10000);
  } catch (InterruptedException e) {
  }
  service.shutdownNow();
 }
 public static void main(String[] args) {
  BlockingQueueTest.testBasket();
 }
}


Related articles: