延迟队列

1 任务类

public class WorkerA implements Runnable {
    @Override
    public void run() {
        //相关业务逻辑处理
        System.out.println(Thread.currentThread().getName() + "A业务处理");
    }
}

public class WorkerB implements Runnable {
    @Override
    public void run() {
        //相关业务逻辑处理
        System.out.println(Thread.currentThread().getName() + "B业务处理");
    }
}

 

2 按照任务类组装的消息体类

import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

public class DelayOrderTask<T extends Runnable> implements Delayed {

    private final long delay;
    private final T task;

    public DelayOrderTask(long timeout, T task) {
        this.delay = System.nanoTime() + timeout;
        this.task = task;
    }

    @Override
    public long getDelay(TimeUnit unit) {
        return unit.convert(this.delay - System.nanoTime(), TimeUnit.NANOSECONDS);
    }

    @Override
    public int compareTo(Delayed o) {
        return (int) (this.getDelay(TimeUnit.MILLISECONDS) - o.getDelay(TimeUnit.MILLISECONDS));
    }

    public T getTask() {
        return task;
    }
}

 3 延迟队列管理类

public class DelayOrderQueueManager {

    private static final int DEFAULT_THREAD_NUM = 5;

    /**
     * 固定大小线程池
     */
    private static final ExecutorService executor = Executors.newFixedThreadPool(DEFAULT_THREAD_NUM);

    /**
     * 延时队列
     */
    private static final DelayQueue<DelayOrderTask<?>> delayQueue = new DelayQueue<>();

    private static final DelayOrderQueueManager instance = new DelayOrderQueueManager();

    public static DelayOrderQueueManager getInstance() {
        return instance;
    }

    private DelayOrderQueueManager() {
        // 守护线程
        Thread daemonThread = new Thread(this::execute);
        daemonThread.setName("DelayQueueMonitor");
        daemonThread.start();
    }

    private void execute() {
        while (true) {
            try {
                DelayOrderTask<?> delayOrderTask = delayQueue.take();
                Runnable task = delayOrderTask.getTask();
                if (null == task) {
                    continue;
                }
                executor.execute(task);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 添加任务
     *
     * @param task
     * @param time 延时时间
     * @param unit 时间单位
     */
    public void put(Runnable task, long time, TimeUnit unit) {
        // 获取延时时间
        long timeout = TimeUnit.NANOSECONDS.convert(time, unit);
        // 将任务封装成实现Delayed接口的消息体
        DelayOrderTask<?> delayOrder = new DelayOrderTask<>(timeout, task);
        // 将消息体放到延时队列中
        delayQueue.put(delayOrder);
    }
    public void put(DelayOrderTask<?> delayOrder){
        delayQueue.put(delayOrder);
    }

    /**
     * 删除任务
     *
     * @param task
     * @return
     */
    public boolean removeTask(DelayOrderTask<?> delayOrder) {
        return delayQueue.remove(delayOrder);
    }
}

 

Test 

public class Test {
    public static void main(String[] args) {
        // 延迟队列管理类,将任务转化消息体并将消息体放入延迟对列中等待执行
        DelayOrderQueueManager manager = DelayOrderQueueManager.getInstance();

        DelayOrderTask<?> t1 = new DelayOrderTask<>(TimeUnit.NANOSECONDS.convert(1000, TimeUnit.MILLISECONDS), new WorkerA());
//        DelayOrderTask<?> t2 = new DelayOrderTask<>(TimeUnit.NANOSECONDS.convert(2000, TimeUnit.MILLISECONDS), new WorkerA());
//        DelayOrderTask<?> t3 = new DelayOrderTask<>(TimeUnit.NANOSECONDS.convert(3000, TimeUnit.MILLISECONDS), new WorkerB());
//        DelayOrderTask<?> t4 = new DelayOrderTask<>(TimeUnit.NANOSECONDS.convert(4000, TimeUnit.MILLISECONDS), new WorkerA());

        manager.put(t1);
        manager.put(t1);
        manager.put(t1);
        manager.put(t1);

        manager.removeTask(t1);
        manager.removeTask(t1);
        manager.removeTask(t1);
        manager.removeTask(t1);
    }
}

 

posted on 2021-06-11 14:50  1zfang1  阅读(103)  评论(0编辑  收藏  举报

导航