gpt4 book ai didi

java - 如何使用 ThreadPoolExecutor 和自定义任务实现 PriorityBlockingQueue

转载 作者:IT老高 更新时间:2023-10-28 20:28:36 25 4
gpt4 key购买 nike

我进行了很多搜索,但找不到解决问题的方法。

我有自己的类 BaseTask,它使用 ThreadPoolExecutor 来处理任务。我想要任务优先级,但是当我尝试使用 PriorityBlockingQueue 我得到 ClassCastException 因为 ThreadPoolExecutor 将我的任务包装到 FutureTask 对象。

这显然是有道理的,因为 FutureTask 没有实现 Comparable,但我将如何继续解决优先级问题?我读到您可以在 ThreadPoolExecutor 中覆盖 newTaskFor(),但我似乎根本找不到这个方法...?

任何建议将不胜感激!

一些帮助的代码:

在我的 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);
}

BaseThreadPoolExecutor 类中,我覆盖了 3 个 submit 方法...该类中的构造函数被调用,但没有任何 submit 方法

最佳答案

public class ExecutorPriority {

public static void main(String[] args) {

PriorityBlockingQueue<Runnable> pq = new PriorityBlockingQueue<Runnable>(20, new ComparePriority());

Executor exe = new ThreadPoolExecutor(1, 2, 10, TimeUnit.SECONDS, pq);
exe.execute(new RunWithPriority(2) {

@Override
public void run() {

System.out.println(this.getPriority() + " started");
try {
Thread.sleep(3000);
} catch (InterruptedException ex) {
Logger.getLogger(ExecutorPriority.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println(this.getPriority() + " finished");
}
});
exe.execute(new RunWithPriority(10) {

@Override
public void run() {
System.out.println(this.getPriority() + " started");
try {
Thread.sleep(3000);
} catch (InterruptedException ex) {
Logger.getLogger(ExecutorPriority.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println(this.getPriority() + " finished");
}
});

}

private static class ComparePriority<T extends RunWithPriority> implements Comparator<T> {

@Override
public int compare(T o1, T o2) {
return o1.getPriority().compareTo(o2.getPriority());
}
}

}

你可以猜到 RunWithPriority 是一个可运行的抽象类,并且有一个整数优先级字段

关于java - 如何使用 ThreadPoolExecutor 和自定义任务实现 PriorityBlockingQueue,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3545623/

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