我有以下据称是 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);
    }
}

但它打印
half second
two seconds
one second

这显然是错误的。

最佳答案

这个错误是一个微妙的错误。我假设 iteratorDelayQueue 将为每个元素执行一系列 take 调用。 错!

请参阅 iterator() JavaDoc:



这是相当出乎意料的。

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

    while (queue.size() > 0) {
        System.out.println(queue.take());
    }

请注意,如果您尝试流式传输队列,也会发生此问题:
    queue.stream().forEach((d) -> {
        System.out.println(d);
    });

由于流将发生在 iterator 提供的 DelayQueue 上,这也会产生意想不到的结果。

关于java - 为什么我的 DelayQueue 没有以错误的顺序延迟和打印?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32206562/

10-11 20:09