DelayQueue延时队列的使用

一、简介
   DelayQueue 是一个无界阻塞队列,添加进去的元素必须实现Delayed接口,而且只有在延迟期满时才能从中提取元素。

二、使用

  1. 实现Delayed接口类
package delayqueue;

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

public class DelayedInfo implements Delayed {

	private int type;
	private long executeTime;

	public DelayedInfo(int type, long executeTime) {
		super();
		this.type = type;
		this.executeTime = executeTime;
	}

	@Override
	public int compareTo(Delayed o) {
		DelayedInfo delayedInfo = (DelayedInfo) o;
		return String.valueOf(executeTime).compareTo(String.valueOf(delayedInfo.getExecuteTime()));
	}

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

	public long getExecuteTime() {
		return executeTime;
	}

	public void setExecuteTime(long executeTime) {
		this.executeTime = executeTime;
	}

	public int getType() {
		return type;
	}

	public void setType(int type) {
		this.type = type;
	}

}

 2.生产者

package delayqueue;

import java.util.concurrent.DelayQueue;

public class DelayQueueProducer {

	private final DelayQueue queue = new DelayQueue<>();

	public DelayQueue getQueue() {
		long currentTime = System.currentTimeMillis();
		queue.offer(new DelayedInfo(1,currentTime + 10000));
		queue.offer(new DelayedInfo(2,currentTime + 5000));
		queue.offer(new DelayedInfo(3,currentTime + 8000));
		return queue;
	}

}

 3.消费者

package delayqueue;

import java.time.LocalTime;
import java.util.concurrent.DelayQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class DelayQueueConsumer {

	public static void main(String[] args) {

		DelayQueueProducer producer = new DelayQueueProducer();
		DelayQueue delayQueue = producer.getQueue();

		System.out.println("当前时间为 : " + LocalTime.now() + ", 准备执行延时队列...");
		ExecutorService service = Executors.newSingleThreadExecutor();
		service.execute(() -> {
			while (true) {
				try {
					DelayedInfo delayedInfo = delayQueue.take();
					System.out.println("执行时间为 : " + LocalTime.now() + ", current type : " + delayedInfo.getType());
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});

	}
}

 三、执行结果

DelayQueue延时队列的使用_第1张图片

由此可见,执行结果的顺序跟compareTo()方法有关,compareTo()用于延迟队列内部比较排序。

你可能感兴趣的:(JUC,DelayQueue,延时队列)