DelayQueue
DelayQueue works with a Delayed object is a synchronised collection. It's like a Primary Queue that sorted in the order of expiration
When you call take()
the queue wait until a certain Delayed
object has been expired before poll it so it introduce a delay
package misc;
import java.util.concurrent.*;
public class Application {
public static void main(String[] args) throws InterruptedException {
DelayQueue<DelayObject> map = new DelayQueue<>();
map.add(new DelayObject("hi", 400));
map.add(new DelayObject("hello", 300));
map.add(new DelayObject("chao", 100));
map.add(new DelayObject("yes", 200));
System.out.println(map);
System.out.println(map.take().data);
System.out.println(map.take().data);
System.out.println(map.take().data);
System.out.println(map.take().data);
}
}
class DelayObject implements Delayed {
public String data;
private long startTime;
public DelayObject(String data, long delayInMilliseconds) {
this.data = data;
this.startTime = System.currentTimeMillis() + delayInMilliseconds;
}
@Override
public long getDelay(TimeUnit unit) {
long diff = startTime - System.currentTimeMillis();
return unit.convert(diff, TimeUnit.MILLISECONDS);
}
@Override
public int compareTo(Delayed o) {
return (int) (this.startTime - ((DelayObject) o).startTime);
}
}
[misc.DelayObject@764c12b6, misc.DelayObject@c387f44, misc.DelayObject@4e0e2f2a, misc.DelayObject@73d16e93]
chao
yes
hello
hi