本文介绍了AsyncTask的关于执行人和的PriorityBlockingQueue的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图做一些AsyncTask的与优先级同时运行。

I'm trying to make some ASyncTask to run simultaneously with a priority.

我创建具有的PriorityBlockingQueue一个的ThreadPoolExecutor和propper比较不错的工作为标准的Runnable。但是打电话时

I've creating a ThreadPoolExecutor with an PriorityBlockingQueue and the propper comparator works nice for standard Runnables.But when calling

    new Task().executeOnExecutor(threadPool, (Void[]) null);

中的PriorityBlockingQueue的比较器接收一个​​Ru​​nnable(私人)内部的AsyncTask的(源$ C ​​$ C称为mFuture)的,所以在比较,我不能确定可运行或阅读优先的价值。

The Comparator of the PriorityBlockingQueue receives a Runnable (private) internal of the ASyncTask (called mFuture in the source code), so in the comparator I can't identify the runnables or read a "priority" value.

我该如何解决呢?谢谢

推荐答案

从<一个借源$ C ​​$ C href="https://github.com/android/platform_frameworks_base/blob/master/core/java/android/os/AsyncTask.java">android.os.AsyncTask并制作自己的com.company.AsyncTask的实现,在这里你可以控制你想在自己的code一切。

Borrow source code from android.os.AsyncTask and make your own com.company.AsyncTask implementation, where you can control everything you want in your own code.

android.os.AsyncTask也配备了准备烤执行人,THREAD_POOL_EXECUTOR和SERIAL_EXECUTOR:

android.os.AsyncTask come with two ready baked executor, THREAD_POOL_EXECUTOR and SERIAL_EXECUTOR:

private static final BlockingQueue<Runnable> sPoolWorkQueue =
        new LinkedBlockingQueue<Runnable>(10);

/**
 * An {@link Executor} that can be used to execute tasks in parallel.
 */
public static final Executor THREAD_POOL_EXECUTOR
        = new ThreadPoolExecutor(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE,
                TimeUnit.SECONDS, sPoolWorkQueue, sThreadFactory);

/**
 * An {@link Executor} that executes tasks one at a time in serial
 * order. This serialization is global to a particular process.
 */
public static final Executor SERIAL_EXECUTOR = new SerialExecutor();

在你的com.company.AsyncTask,创建另一个PRIORITY_THREAD_POOL_EXECUTOR和包装所有你实现这个类中(,你必须visiablity所有内部字段),并使用您AysncTask像这样:

in your com.company.AsyncTask, create another PRIORITY_THREAD_POOL_EXECUTOR and wrap all your implementation within this class (where you have visiablity to all internal fields), and use your AysncTask like so:

com.company.AsyncTask asyncTask = new com.company.AsyncTask();
asyncTask.setPriority(1);
asyncTask.executeOnExecutor(com.company.AsyncTask.PRIORITY_THREAD_POOL_EXECUTOR, (Void[]) null);

看看我的答案here看看我是如何创建自己的AsyncTask使executeOnExecutor()API级别11之前的作品。

Check out my answer here and see how I create my own AsyncTask to make executeOnExecutor() works before API Level 11.

这篇关于AsyncTask的关于执行人和的PriorityBlockingQueue的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-19 01:43