thread40 - DelayQueue

package com.neutron.t22;

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

/**
 *  Queue
 *      DelayQueue  无界队列,什么时候内存填满,就结束
 *      可以做定时执行任务,在添加到DelayQueue队列中会按照执行前后顺序去执行任务
 *  使用put添加到DelayQueue,获取数据时按照特定条件的前后顺序来获取,例子中根据时间先后顺序获取
 */
public class T227DelayQueue {

    static BlockingQueue<MyTask> queue = new DelayQueue();

    static class MyTask implements Delayed {
        long runningTime;

        MyTask (long runningTime) {
            this.runningTime = runningTime;
        }

        @Override
        public long getDelay(TimeUnit unit) {
            return unit.convert(runningTime - System.currentTimeMillis(), TimeUnit.MILLISECONDS);
        }

        @Override
        public int compareTo(Delayed o) {
            if (this.getDelay(TimeUnit.MILLISECONDS) < o.getDelay(TimeUnit.MILLISECONDS)) {
                return -1;
            } else if (this.getDelay(TimeUnit.MILLISECONDS) > o.getDelay(TimeUnit.MILLISECONDS)) {
                return 1;
            } else {
                return 0;
            }
        }

        @Override
        public String toString() {
            return this.runningTime+ "";
        }
    }

    /*
         [1497592892838, 1497592893338, 1497592893838, 1497592894838, 1497592894338]
          1497592892838
          1497592893338
          1497592893838
          1497592894338
          1497592894838
     */
    public static void main(String[] args) throws InterruptedException {
        long now = System.currentTimeMillis();
        MyTask task1 = new MyTask(now + 1000);
        MyTask task2 = new MyTask(now + 2000);
        MyTask task3 = new MyTask(now + 1500);
        MyTask task4 = new MyTask(now + 2500);
        MyTask task5 = new MyTask(now + 500);

        queue.put(task1);
        queue.put(task2);
        queue.put(task3);
        queue.put(task4);
        queue.put(task5);

        System.out.println(queue);

        for (int i = 0; i < 5; i++) {
            System.out.println(queue.take());
        }
    }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值