我正在尝试使ThreadPoolExecutor具有优先权。所以我定义一个

private static ThreadPoolExecutor threadpool = new ThreadPoolExecutor(30, MAXPOOL,  MAXPOOL, TimeUnit.SECONDS,
     queue, new mThreadFactory());

因此,关键是现在的队列引用。但是当我声明:
static PriorityBlockingQueue<mDownloadThread> queue=new PriorityBlockingQueue<mDownloadThread>(MAXPOOL,new DownloadThreadComparator());

编译器在第一行给出错误:构造函数ThreadPoolExecutor(int,int,int,TimeUnit,PriorityBlockingQueue,FileAccess.mThreadFactory)是未定义的,具有一个快速修复程序:将“队列”的类型更改为BlockingQueue。您能帮助我了解问题所在吗?

谢谢

附加信息:

为了比较可运行对象,我实现了以下类
class mDownloadThread implements Runnable{
    private Runnable mRunnable;
    private int priority;
    mDownloadThread(Runnable runnable){
        mRunnable=runnable;
    }

    @Override
    public void run() {
        mRunnable.run();
    }

    public int getPriority() {
        return priority;
    }

    public void setPriority(int priority) {
        this.priority = priority;
    }
}

比较器:
class DownloadThreadComparator implements Comparator<mDownloadThread>{
    @Override
    public int compare(mDownloadThread arg0, mDownloadThread arg1) {

    if (arg0==null && arg1==null){
        return 0;
    } else if (arg0==null){
        return -1;
    } else if (arg1==null){
        return 1;
    }
    return arg0.getPriority()-arg1.getPriority();

    }

}

最佳答案

ThreadPoolExecutor构造函数接受BlockingQueue<Runnable>而不是BlockingQueue<? extends Runnable>,因此您不能将PriorityBlockingQueue<mDownloadThread>实例传递给它。

您可以将queue的类型更改为PriorityBlockingQueue<Runnable>,但是在这种情况下,如果不将其转换为Comparator<mDownloadThread>方法,就无法实现compare

另一个解决方案是绕过通用类型检查,但是您有责任仅将mDownloadThread实例提交给execute方法:

static ThreadPoolExecutor threadpool = new ThreadPoolExecutor(30, MAXPOOL,
        MAXPOOL, TimeUnit.SECONDS, (PriorityBlockingQueue) queue, new mThreadFactory());

关于java - Java(Android)中的优先ThreadPoolExecutor,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/7792767/

10-12 06:06