Data Structure Visualization
public interface Delayed extends Comparable {
//getDelay 方法返回的是“还剩下多长的延迟时间才会被执行”,
//如果返回 0 或者负数则代表任务已过期。
//元素会根据延迟时间的长短被放到队列的不同位置,越靠近队列头代表越早过期。
long getDelay(TimeUnit unit);
}
public class DelayQueueExample {
public static void main(String[] args) throws InterruptedException {
DelayQueue delayQueue = new DelayQueue<>();
// 添加三个订单,分别延迟 5 秒、2 秒和 3 秒
delayQueue.put(new Order("order1", System.currentTimeMillis(), 5000));
delayQueue.put(new Order("order2", System.currentTimeMillis(), 2000));
delayQueue.put(new Order("order3", System.currentTimeMillis(), 3000));
// 循环取出订单,直到所有订单都被处理完毕
while (!delayQueue.isEmpty()) {
Order order = delayQueue.take();
System.out.println("处理订单:" + order.getOrderId());
}
}
static class Order implements Delayed{
private String orderId;
private long createTime;
private long delayTime;
public Order(String orderId, long createTime, long delayTime) {
this.orderId = orderId;
this.createTime = createTime;
this.delayTime = delayTime;
}
public String getOrderId() {
return orderId;
}
@Override
public long getDelay(TimeUnit unit) {
long diff = createTime + delayTime - System.currentTimeMillis();
return unit.convert(diff, TimeUnit.MILLISECONDS);
}
@Override
public int compareTo(Delayed o) {
long diff = this.getDelay(TimeUnit.MILLISECONDS) - o.getDelay(TimeUnit.MILLISECONDS);
return Long.compare(diff, 0);
}
}
}
//用于保证队列操作的线程安全
private final transient ReentrantLock lock = new ReentrantLock();
// 优先级队列,存储元素,用于保证延迟低的优先执行
private final PriorityQueue q = new PriorityQueue();
// 用于标记当前是否有线程在排队(仅用于取元素时) leader 指向的是第一个从队列获取元素阻塞的线程
private Thread leader = null;
// 条件,用于表示现在是否有可取的元素 当新元素到达,或新线程可能需要成为leader时被通知
private final Condition available = lock.newCondition();
public DelayQueue() {}
public DelayQueue(Collection extends E> c) {
this.addAll(c);
}
public void put(E e) {
offer(e);
}
public boolean offer(E e) {
final ReentrantLock lock = this.lock;
lock.lock();
try {
// 入队
q.offer(e);
if (q.peek() == e) {
// 若入队的元素位于队列头部,说明当前元素延迟最小
// 将 leader 置空
leader = null;
// available条件队列转同步队列,准备唤醒阻塞在available上的线程
available.signal();
}
return true;
} finally {
lock.unlock(); // 解锁,真正唤醒阻塞的线程
}
}
public E take() throws InterruptedException {
final ReentrantLock lock = this.lock;
lock.lockInterruptibly();
try {
for (;;) {
E first = q.peek();// 取出堆顶元素( 最早过期的元素,但是不弹出对象)
if (first == null)// 如果堆顶元素为空,说明队列中还没有元素,直接阻塞等待
available.await();//当前线程无限期等待,直到被唤醒,并且释放锁。
else {
long delay = first.getDelay(NANOSECONDS);// 堆顶元素的到期时间
if (delay <= 0)// 如果小于0说明已到期,直接调用poll()方法弹出堆顶元素
return q.poll();
// 如果delay大于0 ,则下面要阻塞了
// 将first置为空方便gc
first = null;
// 如果有线程争抢的Leader线程,则进行无限期等待。
if (leader != null)
available.await();
else {
// 如果leader为null,把当前线程赋值给它
Thread thisThread = Thread.currentThread();
leader = thisThread;
try {
// 等待剩余等待时间
available.awaitNanos(delay);
} finally {
// 如果leader还是当前线程就把它置为空,让其它线程有机会获取元素
if (leader == thisThread)
leader = null;
}
}
}
}
} finally {
// 成功出队后,如果leader为空且堆顶还有元素,就唤醒下一个等待的线程
if (leader == null && q.peek() != null)
// available条件队列转同步队列,准备唤醒阻塞在available上的线程
available.signal();
// 解锁,真正唤醒阻塞的线程
lock.unlock();
}
}
public class BlockingQueueExample {
private static final int QUEUE_CAPACITY = 5;
private static final int PRODUCER_DELAY_MS = 1000;
private static final int CONSUMER_DELAY_MS = 2000;
public static void main(String[] args) throws InterruptedException {
// 创建一个容量为QUEUE_CAPACITY的阻塞队列
BlockingQueue queue = new ArrayBlockingQueue<>(QUEUE_CAPACITY);
// 创建一个生产者线程
Runnable producer = () -> {
while (true) {
try {
// 在队列满时阻塞
queue.put("producer");
System.out.println("生产了一个元素,队列中元素个数:" + queue.size());
Thread.sleep(PRODUCER_DELAY_MS);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
new Thread(producer).start();
// 创建一个消费者线程
Runnable consumer = () -> {
while (true) {
try {
// 在队列为空时阻塞
String element = queue.take();
System.out.println("消费了一个元素,队列中元素个数:" + queue.size());
Thread.sleep(CONSUMER_DELAY_MS);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
new Thread(consumer).start();
}
}
public class FlowControl {
private static final int MAX_REQUESTS = 100; // 最大请求数量
private static final int MAX_WAIT_TIME = 1000; // 最大等待时间(毫秒)
private static final ArrayBlockingQueue
public class DelayQueueExample {
public static void main(String[] args) throws InterruptedException {
DelayQueue delayQueue = new DelayQueue<>();
// 添加三个订单,分别延迟 5 秒、2 秒和 3 秒
delayQueue.put(new Order("order1", System.currentTimeMillis(), 5000));
delayQueue.put(new Order("order2", System.currentTimeMillis(), 2000));
delayQueue.put(new Order("order3", System.currentTimeMillis(), 3000));
// 循环取出订单,直到所有订单都被处理完毕
while (!delayQueue.isEmpty()) {
Order order = delayQueue.take();
System.out.println("处理订单:" + order.getOrderId());
}
}
static class Order implements Delayed{
private String orderId;
private long createTime;
private long delayTime;
public Order(String orderId, long createTime, long delayTime) {
this.orderId = orderId;
this.createTime = createTime;
this.delayTime = delayTime;
}
public String getOrderId() {
return orderId;
}
@Override
public long getDelay(TimeUnit unit) {
long diff = createTime + delayTime - System.currentTimeMillis();
return unit.convert(diff, TimeUnit.MILLISECONDS);
}
@Override
public int compareTo(Delayed o) {
long diff = this.getDelay(TimeUnit.MILLISECONDS) - o.getDelay(TimeUnit.MILLISECONDS);
return Long.compare(diff, 0);
}
}
}