Add*_*dev 6 java multithreading android thread-safety
我正在尝试优先创建一个ThreadPoolExecutor.所以我定义了一个
private static ThreadPoolExecutor threadpool = new ThreadPoolExecutor(30, MAXPOOL, MAXPOOL, TimeUnit.SECONDS,
queue, new mThreadFactory());
Run Code Online (Sandbox Code Playgroud)
所以关键是现在的队列引用.但是当我宣布:
static PriorityBlockingQueue<mDownloadThread> queue=new PriorityBlockingQueue<mDownloadThread>(MAXPOOL,new DownloadThreadComparator());
Run Code Online (Sandbox Code Playgroud)
编译器在第一行中给出错误:构造函数ThreadPoolExecutor(int,int,int,TimeUnit,PriorityBlockingQueue,FileAccess.mThreadFactory)未使用单个quickfix进行定义:将"queue"类型更改为BlockingQueue.你能帮我理解这个问题吗?
谢谢
附加信息:
为了比较runnables,我实现了以下类
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;
}
}
Run Code Online (Sandbox Code Playgroud)
比较器:
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();
}
}
Run Code Online (Sandbox Code Playgroud)
ThreadPoolExecutor构造函数接受BlockingQueue<Runnable>而不是BlockingQueue<? extends Runnable>,因此您无法传递给它PriorityBlockingQueue<mDownloadThread>实例.
您可以更改类型queue到PriorityBlockingQueue<Runnable>,但在这种情况下,你将无法实现Comparator<mDownloadThread>无内铸造compare方法.
另一种解决方案是绕过泛型类型检查,但是您只需要提交mDownloadThreadto execute方法的实例:
static ThreadPoolExecutor threadpool = new ThreadPoolExecutor(30, MAXPOOL,
MAXPOOL, TimeUnit.SECONDS, (PriorityBlockingQueue) queue, new mThreadFactory());
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3187 次 |
| 最近记录: |