Java Concurrent Programming Tool JUC Part 3: DelayQueue Delay Queue

DelayQueue is the implementation class of the BlockingQueue interface. It determines the processing priority of the elements in the queue according to the "delay time" (that is, sorts according to the "delay time" of the queue elements). Another meaning is that only those elements that exceed the "delay time" can be taken out of the queue for processing.

  • The DelayQueue queue will prevent its element objects from being taken out of the queue until the delay time set for the element objects is reached. DelayQueue stores the most recently expired elements at the head of the queue. If no element in the queue expires, using the poll() method to get the elements in the queue will return null.
  • The DelayQueue class and its iterator implement all optional methods of the Collection and Iterator interfaces, but the iterator method iterator()cannot guarantee to traverse the DelayQueue elements in a specific order.

  • DelayQueue does not receive null elements. DelayQueue only accepts objects that implement the java.util.concurrent.Delayed interface and puts them in the queue. DelayQueue obtains the remaining "delay time" of the element by calling the getDelay(TimeUnit) method of the element object. The TimeUnit time unit of getDelay() is an enumerated type: DAYS (days), HOURS (hours), MINUTES (minutes), SECONDS (seconds), MILLISECONDS (milliseconds), MICROSECONDS (microseconds), NANOSECONDS (nanoseconds)
public interface Delayed extends Comparable{
   long getDelay(TimeUnit unit);
}

Next, we will write a java Class that implements the Delayed interface, and only class objects that implement the Delayed interface can be placed in the DelayQueue. Because the Delayed interface inherits from the Comparable interface, we must implement the getDelay method and the compareTo method.

class DelayObject implements Delayed {
    private String name; 
    private long time;   //延时时间

    public DelayObject(String name, long delayTime) { 
      this.name = name; 
      this.time = System.currentTimeMillis() + delayTime; 
    } 

   @Override
   public long getDelay(TimeUnit unit) {
      long diff = time - System.currentTimeMillis(); 
      return unit.convert(diff, TimeUnit.MILLISECONDS); 
   } 

   @Override
   public int compareTo(Delayed obj) { 
      if (this.time < ((DelayObject)obj).time) { 
         return -1; 
      } 
      if (this.time > ((DelayObject)obj).time) { 
         return 1; 
      } 
      return 0; 
   } 

   @Override
   public String toString() {
     Date date = new Date(time);
     SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

     return "\nDelayObject:{"
       + "name=" + name
       + ", time=" +  sd.format(date)
       + "}";
   } 
} 

Test the use effect of DelayQueue

public class DelayQueueTest {

  @Test
  void testDelayObject() throws InterruptedException {

    //实例化一个DelayQueue
    BlockingQueue<DelayObject> DQ = new DelayQueue<>();

    //向DelayQueue添加四个元素对象,注意延时时间不同
    DQ.add(new DelayObject("A", 1000 * 10));  //延时10秒
    DQ.add(new DelayObject("B", 4000 * 10));  //延时40秒
    DQ.add(new DelayObject("C", 3000 * 10));  //延时30秒
    DQ.add(new DelayObject("D", 2000 * 10));  //延时20秒

    SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    //将对象从DelayQueue取出,注意取出的顺序与延时时间有关
    System.out.println( DQ.take());  //取出A
    System.out.println( DQ.take());  //取出D
    System.out.println( DQ.take());  //取出C
    System.out.println( DQ.take());  //取出B

  }
}

It can be seen from the print result below and the code above

  • The order of placing the elements in the queue is A, B, C, D, and the order of taking out is A, D, C, B, this is because the elements in the queue are sorted according to the delay time.
  • In addition, we can see that an element can be taken out of the queue every 10 seconds. This is because only elements that exceed the "delay time" can be taken out of the queue. And the delay time we set is 10s, 20s, 30s, 40s.
DelayObject:{name=A, time=2021-03-23 14:14:20}

DelayObject:{name=D, time=2021-03-23 14:14:30}

DelayObject:{name=C, time=2021-03-23 14:14:40}

DelayObject:{name=B, time=2021-03-23 14:14:50}

Welcome to follow my blog, there are many boutique collections

  • This article is reproduced indicate the source (en must not turn only the text): letters Gebo off .

If you think it is helpful to you, please like and share it for me! Your support is my inexhaustible creative motivation! . In addition, the author has output the following high-quality content recently, and I look forward to your attention.

Guess you like

Origin blog.csdn.net/hanxiaotongtong/article/details/115157074