java DelayQueue

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

class DelayObj implements Delayed {

    private long delayTime;
    private long expire;
    private String data;

    public DelayObj(int delayTime, String data) {
        this.data = data;
        delayTime = delayTime;
        expire += System.currentTimeMillis() + delayTime;
    }

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

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

    public void sayHello() {
        System.out.println("在这个时刻:" + new Date().toLocaleString() + "被执行===>" + data);
    }
}

public class MyDelayQueueTest {
    public static void main(String[] args) throws InterruptedException {
        DelayQueue delayQueue = new DelayQueue<>();

        DelayObj wumiaozhongDelay = new DelayObj(5,"五秒钟后执行的线程");
        DelayObj shimiaozhongDelay = new DelayObj(10,"十秒钟后执行的线程");

        delayQueue.offer(wumiaozhongDelay);
        delayQueue.offer(shimiaozhongDelay);

        DelayObj result = delayQueue.take();
        result.sayHello();
        result = delayQueue.take();
        result.sayHello();

        System.out.println("证明队列里的东西被取光之前,是阻塞的");





    }
}

你可能感兴趣的:(Java)