gpt4 book ai didi

java - Java (Android) 中的优先级 ThreadPoolExecutor

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:41:43 26 4
gpt4 key购买 nike

我正在尝试创建一个具有优先级的 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) is undefined with a single quickfix: Change type “队列”到 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com