zoukankan      html  css  js  c++  java
  • DelayQueue使用实例

    DelayQueue是延迟阻塞队列。这种特性可以让我们做一些ArrayBlockingQueue、LinkedBlockingQueue这种常规阻塞队列所做不到的事情。比如说银行转账24h后才到账,微信转账2h到账或者24小时到账。

    public class DelayQueueTest {
    
        public static void main(String[] args) {
            DelayQueue<MyTimerRunnable> blockingQueue = new DelayQueue<>();
    
            blockingQueue.put(new MyTimerRunnable(System.currentTimeMillis() + 10 * 1000,
                    () -> System.out.println(10)));
    
            blockingQueue.put(new MyTimerRunnable(System.currentTimeMillis() + 5 * 1000,
                    () -> System.out.println(5)));
    
            blockingQueue.put(new MyTimerRunnable(System.currentTimeMillis() + 15 * 1000,
                    () -> System.out.println(15)));
            System.out.println("开始---" + System.currentTimeMillis());
            for (; ; ) {
                try {
                    MyTimerRunnable timerRunnable = blockingQueue.take();
                    System.out.println("处理---" + System.currentTimeMillis());
                    Runnable runnable = timerRunnable.getRunnable();
                    if (runnable != null) {
                        runnable.run();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    MyTimerRunnable是我们自定义的Delayed接口的实现类,里面定义了一些属性,包括执行时间以及执行的任务。自定义类必须实现Delayed接口的getDelay()方法和Delayed接口继承自Comoarable接口的compareTo()方法。

    public class MyTimerRunnable implements Delayed {
    
        private long processTime;
    
        private Runnable runnable;
    
        public long getProcessTime() {
            return processTime;
        }
    
        public Runnable getRunnable() {
            return runnable;
        }
    
        public MyTimerRunnable(long processTime, Runnable runnable) {
            this.processTime = processTime;
            this.runnable = runnable;
        }
    
        @Override
        public long getDelay(@NotNull TimeUnit unit) {
            return processTime - System.currentTimeMillis();
        }
    
        @Override
        public int compareTo(@NotNull Delayed o) {
            return (int) (getProcessTime() - ((MyTimerRunnable) o).getProcessTime());
        }
    
    }

    打印结果是

    开始---1584076398361
    处理---1584076403361
    5
    处理---1584076408322
    10
    处理---1584076413361
    15

  • 相关阅读:
    poj2104 Kth-Number
    bzoj2120 数颜色
    hdu5145 NPY and girls
    bzoj2734 集合选数
    bzoj3732 NetWork
    bzoj2152 聪聪可可
    hdu2036(多边形面积)
    超大次幂思路
    hdu 2030 统计汉字个数
    Hibernate 配置文件与映射文件 总结
  • 原文地址:https://www.cnblogs.com/koushr/p/9483834.html
Copyright © 2011-2022 走看看