我是并发编程的新手。我创建了两个类DelayedElement.java和DelayQueueExample,以如下了解DelayQueue:

import java.util.concurrent.DelayQueue;
import java.util.concurrent.Delayed;

public class DelayQueueExample {
    public static void main(String[] args) throws InterruptedException {
        DelayQueue queue = new DelayQueue();
        Delayed element1 = new DelayedElement(5);
        queue.put(element1);
        System.out.println("Put done");
        Delayed element2 = queue.take();
        System.out.println("Take done");
        System.out.println(((DelayedElement)element2).getI());
    }
}


DelayedElement类如下:

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

public class DelayedElement implements Delayed {

    private int i;
    public DelayedElement(int i) {
        this.setI(i);
    }

    @Override
    public int compareTo(Delayed o) {
        // TODO Auto-generated method stub
        return 0;
    }

    @Override
    public long getDelay(TimeUnit unit) {
        long diff = 10000l;
        return  unit.convert(diff, TimeUnit.MILLISECONDS);
    }

    public int getI() {
        return i;
    }

    public void setI(int i) {
        this.i = i;
    }

}


我运行了程序,输出显示放置完成。但是,当我调用queue.take()操作时,它无限延迟。我在DelayedElement的getDeley方法中将延迟时间指定为10秒。那么为什么我的程序以这种方式运行?有人可以帮我了解我的错吗?

最佳答案

如DelayedQueue的Java文档中所写


  当元素的getDelay(TimeUnit.NANOSECONDS)发生过期
  方法返回小于或等于零的值。


您已重写getDelay(TimeUnit.NANOSECONDS)方法,使其始终返回恒定延迟。您应该更改它,以使延迟随时间减少。

就像是

// startTime is some future time set while creating delay element.
public long getDelay(TimeUnit unit) {
        long diff = startTime - System.currentTimeMillis();
        return unit.convert(diff, TimeUnit.MILLISECONDS);
}

10-06 15:32