为什么我的DelayQueue不会以错误的顺序延迟和打印?

Old*_*eon 4 java

我有以下假设的一个简单的DelayQueue演示.

class DelayedThing implements Delayed {

    private final long waitUntil;
    private final String name;

    public DelayedThing(String name, long wait) {
        this.name = name;
        this.waitUntil = System.currentTimeMillis() + wait;
        System.out.println("DelayedThing(" + name + " wait=" + wait + " until-" + waitUntil);
    }

    @Override
    public long getDelay(TimeUnit unit) {
        System.out.println(name + " getDelay = " + unit.convert(waitUntil - System.currentTimeMillis(), TimeUnit.MILLISECONDS));
        return unit.convert(waitUntil - System.currentTimeMillis(), TimeUnit.MILLISECONDS);
    }

    @Override
    public int compareTo(Delayed o) {
        long diff = this.getDelay(TimeUnit.MILLISECONDS) - o.getDelay(TimeUnit.MILLISECONDS);
        System.out.println(name + ".compareTo(" + o + ") = " + diff);
        return Long.signum(diff);
    }

    @Override
    public String toString() {
        return name;
    }
}

public void test() throws InterruptedException {
    BlockingQueue<Delayed> queue = new DelayQueue<>();
    queue.add(new DelayedThing("one second", 1000));
    queue.add(new DelayedThing("two seconds", 2000));
    queue.add(new DelayedThing("half second", 500));
    for (Delayed d : queue) {
        System.out.println(d);
    }
}
Run Code Online (Sandbox Code Playgroud)

但它打印出来

half second
two seconds
one second
Run Code Online (Sandbox Code Playgroud)

这显然是错的.

Old*_*eon 5

错误是一个微妙的错误.我假设iteratora DelayQueue将执行take每个元素的一系列调用.错误!

请参阅iterator() JavaDoc:

返回此队列中所有元素(已过期和未过期)的迭代器.

这是非常意外的.

一个正确的解决方案如下:

    while (queue.size() > 0) {
        System.out.println(queue.take());
    }
Run Code Online (Sandbox Code Playgroud)

请注意,如果您尝试流式传输队列,也会发生此问题:

    queue.stream().forEach((d) -> {
        System.out.println(d);
    });
Run Code Online (Sandbox Code Playgroud)

由于流式传输将发生在由此iterator提供的DelayQueue也将产生意想不到的结果.