2

请假设以下情况:

public static void main(String[] args) {
    ThreadPoolExecutor pool = new ThreadPoolExecutor(0, 5, 1L, TimeUnit.SECONDS, new PriorityBlockingQueue<Runnable>());
    DashboardHtmlExport d = new DashboardHtmlExport();
    for (int i = 0; i < 40; i++) {
        System.out.println("Submitting: " + i);
        try {
            Thread.sleep(cooldown);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        pool.submit(d.new A(i));
    }
}

private class A implements Runnable, Comparable<A> {
    private int order;

    public A(int order) {
        this.order = order;
    }

    public void run() {
        try {
            Thread.sleep(busyTime);
        } catch (InterruptedException e) {
            System.out.println(e.getMessage());
        }
        System.out.println(new Date());
    }

    public int compareTo(A o) {
        return Integer.valueOf(o.order).compareTo(Integer.valueOf(order));
    }
}

这产生了以下错误:

Submitting: 0
Submitting: 1
Exception in thread "main" java.lang.ClassCastException: java.util.concurrent.FutureTask cannot be cast to java.lang.Comparable
    at java.util.PriorityQueue.siftUpComparable(PriorityQueue.java:578)
    at java.util.PriorityQueue.siftUp(PriorityQueue.java:574)
    at java.util.PriorityQueue.offer(PriorityQueue.java:274)
    at java.util.concurrent.PriorityBlockingQueue.offer(PriorityBlockingQueue.java:164)
    at java.util.concurrent.ThreadPoolExecutor.execute(ThreadPoolExecutor.java:653)
    at java.util.concurrent.AbstractExecutorService.submit(AbstractExecutorService.java:78)
    at com.skycomm.cth.pages.test.DashboardHtmlExport.main(DashboardHtmlExport.java:133)
Tue Jul 10 23:48:45 GMT+02:00 2012

为什么会这样?!

这仅在busyTime时间少于cooldown时间时才有效。这意味着队列不能处理超过 2 个提交的任务!

基本上,我想要做的是拥有一个UNBOUND大小的池,并且可以通过可比较或比较器进行排序。我只能使用 a 来实现UNBOUND队列,LinkedBlockingQueue但这当然是不可排序的!

谢谢你。

4

1 回答 1

11

RunnableFutureThreadPoolExecutor使用newTaskFor()方法将您提交的 Runnable 转换为一个,并将这个 RunnableFuture 添加到队列中。因此,如果您想使用 PriorityQueue,您应该重写该newTaskFor()方法以确保RunnableFuture它创建的实例具有可比性。

或者您也可以使用execute()方法而不是submit()方法来绕过任务创建。

于 2012-07-11T10:34:45.967 回答