Home >Java >javaTutorial >Sample code analysis of blocking queue BlockingQueue in java

Sample code analysis of blocking queue BlockingQueue in java

黄舟
黄舟Original
2017-04-01 10:30:071606browse

This article mainly introduces the detailed explanation and examples of blocking queueBlockingQueue in java. Friends who need it can refer to

The detailed explanation and examples of blocking queue BlockingQueue in java

BlockingQueue is a good solution to the transmission of data in multi-threads. First of all, BlockingQueue is an interface. It has roughly four implementation classes. This is a very special queue. If the BlockQueue is empty, the operation of retrieving things from the BlockingQueue will be blocked and enter the waiting state . It will not be awakened until the BlockingQueue enters something. Similarly, if the BlockingQueue is full, any attempt to save it will The operation of things will also be blocked and enter the waiting state. It will not be awakened to continue the operation until there is space in the BlockingQueue.

Four implementation classes of BlockingQueue:

1.ArrayBlockingQueue: BlockingQueue of specified size, its constructor An int parameter must be taken to indicate its size. The objects it contains are sorted in FIFO (first in, first out) order.

2.LinkedBlockingQueue: BlockingQueue of variable size , if its constructor takes a parameter with a specified size, the generated BlockingQueue has a size limit. If it does not take a size parameter, the size of the generated BlockingQueue is determined by Integer.MAX_VALUE. The objects it contains are based on FIFO (first in, first out) )Sequential sorting

3.PriorityBlockingQueue: Similar to LinkedBlockQueue, but the sorting of the objects it contains is not FIFO, but based on the natural sorting order of the object or the order determined by the Comparator of the constructor.

4.SynchronousQueue: A special BlockingQueue, the operation on which must be completed alternately by putting and taking.

Common methods of BlockingQueue:

  1) add(anObject): Add anObject to the BlockingQueue, that is, if the BlockingQueue can accommodate it, return true, otherwise an exception will be reported

2)offer(anObject ): Indicates that if possible, add anObject to the BlockingQueue, that is, if the BlockingQueue can accommodate it, return true, otherwise return false.

3)put(anObject): Add anObject to the BlockingQueue , if there is no space in the BlockQueue, the thread calling this method is blocked until there is space in the BlockingQueue before continuing. If the first object cannot be taken out immediately, you can wait for the time specified by the time parameter. If it cannot be taken out, it will return
null

5) take(): Take away the object in the BlockingQueue The first-ranked object, if the BlockingQueue is empty, is blocked and enters the waiting state until a new object is added to the Blocking
Example:

This example mainly simulates The workflow between producers and consumers is a simple scenario where consumers wait for producers to produce products for consumers to consume.

Producer:

package com.gefufeng;

import java.util.concurrent.BlockingQueue;

public class Producter implements Runnable{
 private BlockingQueue<String> blockingQueue;
 
 public Producter(BlockingQueue<String> blockingQueue){
 this.blockingQueue = blockingQueue;
 }

 @Override
 public void run() {
 try {
  blockingQueue.put("我生产的" + Thread.currentThread().getName());
  System.out.println("我生产的" + Thread.currentThread().getName());
 } catch (InterruptedException e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
  System.out.println("生产失败");
 }
 
 }
 
 

}

Consumer:

package com.gefufeng;

import java.util.concurrent.BlockingQueue;

public class Customer implements Runnable{
 private BlockingQueue<String> blockingQueue;
 
 public Customer(BlockingQueue<String> blockingQueue){
 this.blockingQueue = blockingQueue;
 }

 @Override
 public void run() {
 for(;;){
  try {
  String threadName = blockingQueue.take();
  System.out.println("取出:" + threadName);
  } catch (InterruptedException e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
  System.out.println("取出失败");
  }
 }
 }

}

Execution class:

package com.gefufeng;

import java.util.concurrent.ArrayBlockingQueue;

public class Executer {
 
 public static void main(String[] args) {
 ArrayBlockingQueue<String> arrayBlockingQueue = new ArrayBlockingQueue<String>(2);
 Producter producter = new Producter(arrayBlockingQueue);
 Customer cusotmer = new Customer(arrayBlockingQueue);
 new Thread(cusotmer).start();
 for(;;){
  try {
  Thread.sleep(2000);
  new Thread(producter).start();
  } catch (InterruptedException e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
  }
 }
 
 
 
 }

}
First is the consumerLoop

Wait for the product. When blockingQueue.take() is executed for the first time in the loop, no product can be obtained, so it enters the blocking state. Two seconds later, the producer produces a product, so the blockingQueue gets the product and prints it. After reading the log, the consumer executed the second loop and found that blockingQueue.take() did not get the product again, so it entered the blocking state again. . . Loop in sequence

The above is the detailed content of Sample code analysis of blocking queue BlockingQueue in java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn