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

我有自己的类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);
}

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是一个可运行的抽象类,并且具有Integer优先级字段

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

10-12 21:48