并发新构件之DelayQueue:延时队列

package com.houjun.current.newClassBank;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.*;

import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static java.util.concurrent.TimeUnit.NANOSECONDS;
import static java.util.concurrent.TimeUnit.SECONDS;

/**
* @Author: HouJun
* @Date: 2019/10/17 15:06
* @Description: 延时队列
* @version: 1.0
*/
class DelayedTask implements Runnable, Delayed {
private static int counter = 0;
private final int id = counter++;
private final int delta;
private final long trigger;//触发器
protected static List sequence = new ArrayList<>();

public DelayedTask(int delayInMilliseconds) {
delta = delayInMilliseconds;
trigger = System.nanoTime() + NANOSECONDS.convert(delta, MILLISECONDS);//转换delta数据的时间单位为纳秒
sequence.add(this);
System.out.println("延时"+getDelay(SECONDS)+"秒");
}

@Override
public long getDelay(TimeUnit unit) {
return unit.convert(trigger - System.nanoTime(), NANOSECONDS);//转换数据从纳秒到 ······接受调用传入的时间单位i
}

@Override
public int compareTo(Delayed o) {
DelayedTask that = (DelayedTask) o;
if (trigger < that.trigger) return -1;
if (trigger > that.trigger) return 1;
return 0;
}

@Override
public void run() {
System.out.println(this + " ");

}

@Override
public String toString() {
return String.format("[%1$-4d]", delta) + " Task " + id;
}

public String summary() {
return "(" + id + ":" + delta + ")";
}

public static class EndSentinel extends DelayedTask {
private ExecutorService executorService;

public EndSentinel(int delayInMilliseconds, ExecutorService e) {
super(delayInMilliseconds);
executorService = e;
}

@Override
public void run() {
for (DelayedTask task : sequence) {
System.out.println(task.summary() + " ");
}
System.out.println();
System.out.println(this + " Calling shutdownNow()");
executorService.shutdownNow();
}
}
}

class DelayedTaskConsumer implements Runnable {
private DelayQueue q;

public DelayedTaskConsumer(DelayQueue q) {
this.q = q;
}

@Override
public void run() {
try {
while (!Thread.interrupted()) {
System.out.println("haha");
DelayedTask delayedTask = q.take();//阻塞在这个位置上说明没有到期
System.out.println("获取后getDelay:"+delayedTask.getDelay(SECONDS));//输出o或负数说明到期
delayedTask.run();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Finished DelayedTaskConsumer");
}
}


public class DelayQueueDemo {
public static void main(String[] args) {
Random random = new Random(47);
ExecutorService executorService = Executors.newCachedThreadPool();
DelayQueue queue = new DelayQueue<>();//使用延时队列
for (int i = 0; i < 20; i++) {
queue.put(new DelayedTask(random.nextInt(50000)));
}
// queue.add(new DelayedTask.EndSentinel(5000, executorService));
executorService.execute(new DelayedTaskConsumer(queue));
// executorService.shutdownNow();
}
}

你可能感兴趣的:(并发新构件之DelayQueue:延时队列)