0

我正在尝试实现“PriorityThreadPoolExecutor”。

所以我声明执行者:

static ThreadPoolExecutor threadPool =  
                new ThreadPoolExecutor(2, 100, 100, TimeUnit.SECONDS, queue); 

优先级的关键是队列参数。基本上我需要一个 PriorityBlockingQueue 所以我使用构造函数:

PriorityBlockingQueue(int initialCapacity, Comparator<? super E> comparator);
queue = new PriorityBlockingQueue<mRunnable>(10,
        new Comparator<mRunnable>() {

            @Override
            public int compare(mRunnable lhs, mRunnable rhs) {
                return rhs.getPriority()-lhs.getPriority();
            }
        });

mRunnable 在哪里:

public interface mRunnable extends Runnable {
    public int getPriority();
}

但是编译器在这里抱怨:

Type mismatch: cannot convert from PriorityBlockingQueue<mRunnable> 
       to PriorityBlockingQueue <Runnable>

我不明白为什么当 mRunnable 扩展 Runnable 时会发生此错误。

我可以修补它来改变比较器:

new Comparator<Runnable>() {

    @Override
    public int compare(Runnable lhs, Runnable rhs) {
        if (lhs instanceof mRunnable && rhs instanceof mRunnable){
        return ((mRunnable)rhs).getPriority()-((mRunnable)lhs).getPriority();
        }
        return 0;
    }
});

但这是一个丑陋的解决方案恕我直言。

你能解释一下为什么会发生类型不匹配吗?谢谢

4

1 回答 1

2

由于不同的通用类型而发生类型不匹配,您应该将引用类型从 更改PriorityBlockingQueue<Runnable>PriorityBlockingQueue <mRunnable>。或者PriorityBlockingQueue<? extends Runnable>例如。

于 2012-08-20T13:03:09.430 回答