如何使用 ThreadPoolExecutor 和自定义任务实现 PriorityBlockingQueue
2022-09-01 17:27:24
我搜索了很多,但找不到解决我的问题的方法。
我有自己的类,它使用 a 来处理任务。我想要任务优先级,但是当我尝试使用一个时,我会得到,因为它将我的任务包装到一个对象中。BaseTask
ThreadPoolExecutor
PriorityBlockingQueue
ClassCastException
ThreadPoolExecutor
FutureTask
这显然是有道理的,因为 没有实现,但是我该如何继续解决优先级问题呢?我已经读到你可以覆盖,但我似乎根本找不到这种方法...?FutureTask
Comparable
newTaskFor()
ThreadPoolExecutor
任何建议将不胜感激!
一些代码可以帮助:
在我的课堂上,我有BaseTask
private static final BlockingQueue<Runnable> sWorkQueue = new PriorityBlockingQueue<Runnable>();
private static final ThreadFactory sThreadFactory = new ThreadFactory() {
private final AtomicInteger mCount = new AtomicInteger(1);
public Thread newThread(Runnable r) {
return new Thread(r, "AsyncTask #" + mCount.getAndIncrement());
}
};
private static final BaseThreadPoolExecutor sExecutor = new BaseThreadPoolExecutor(
1, Integer.MAX_VALUE, 10, TimeUnit.SECONDS, sWorkQueue, sThreadFactory);
private final BaseFutureTask<Result> mFuture;
public BaseTask(int priority) {
mFuture = new BaseFutureTask<Result>(mWorker, priority);
}
public final BaseTask<Params, Progress, Result> execute(Params... params) {
/* Some unimportant code here */
sExecutor.execute(mFuture);
}
在课堂上BaseFutureTask
@Override
public int compareTo(BaseFutureTask another) {
long diff = this.priority - another.priority;
return Long.signum(diff);
}
在类 i 中,重写 3 种方法...调用此类中的构造函数,但未调用任何方法BaseThreadPoolExecutor
submit
submit