package com.logicbig.example.delayqueue;
import java.util.concurrent.DelayQueue;
import java.util.concurrent.Delayed;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
public class AddExample {
public static void main(String... args) throws InterruptedException {
DelayQueue<Task> queue = new DelayQueue<>();
queue.add(new Task(1));
queue.add(new Task(2));
queue.add(new Task(3));
queue.forEach(System.out::println);//for each is not the taking order
System.out.println("taking from queue");
for (int i = 0; i < 3; i++) {
Task task = queue.take();
System.out.println(task);
}
}
private static class Task implements Delayed {
private final long end;
private final int expectedDelay;
private int id;
Task(int id) {
this.id = id;
expectedDelay = ThreadLocalRandom.current().nextInt(100, 1000);
end = System.currentTimeMillis() + expectedDelay;
}
@Override
public long getDelay(TimeUnit unit) {
return unit.convert(end - System.currentTimeMillis(),
TimeUnit.MILLISECONDS);
}
@Override
public int compareTo(Delayed o) {
return Long.compare(this.getDelay(TimeUnit.MILLISECONDS),
o.getDelay(TimeUnit.MILLISECONDS));
}
public int getExpectedDelay() {
return expectedDelay;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Override
public String toString() {
return "Task{" +
"expectedDelay=" + expectedDelay +
", id=" + id +
'}';
}
}
}
Output
Task{expectedDelay=245, id=1}
Task{expectedDelay=957, id=2}
Task{expectedDelay=541, id=3}
taking from queue
Task{expectedDelay=245, id=1}
Task{expectedDelay=541, id=3}
Task{expectedDelay=957, id=2}