标签:over new rgs str pack private package tac 结束时间
package com.dh.learn.queue; import java.util.concurrent.DelayQueue; import java.util.concurrent.Delayed; import java.util.concurrent.TimeUnit; public class LearnDelayQueue { // DelayQueue 只能放置实现了Delayed接口的元素 底层使用的是PriorityQueue //1. 在put时加了ReentrantLock,保证线程安全,由于是无界队列,在put时不会发生阻塞 //2. 在take时,根据每个Delayed元素的延时,利用Condition去await对应的时间,直到Delayed元素的延时为0时,就可以取出元素了。 public static void main(String[] args) { DelayQueue<MyDelay> delayQueue = new DelayQueue<>(); delayQueue.put(new MyDelay("111")); delayQueue.put(new MyDelay("222")); delayQueue.put(new MyDelay("333")); delayQueue.put(new MyDelay("444")); System.out.println("开始时间" + System.currentTimeMillis()); try { delayQueue.take(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("结束时间" + System.currentTimeMillis()); } static class MyDelay implements Delayed { private String name; private long start = System.currentTimeMillis(); private long time; public MyDelay(String name) { this.name = name; //1s的延时 this.time = 1000; } @Override public long getDelay(TimeUnit unit) { return unit.convert((start + time) - System.currentTimeMillis(), TimeUnit.MILLISECONDS); } @Override public int compareTo(Delayed o) { return 0; } @Override public String toString() { return super.toString(); } } }
标签:over new rgs str pack private package tac 结束时间
原文地址:https://www.cnblogs.com/han6/p/11308106.html