Executor和PriorityBlockingQueue上的ASyncTask

我正在尝试使一些ASyncTask同时以优先级运行。

我正在创建一个带有PriorityBlockingQueue的ThreadPoolExecutor,并且propper比较器适用于标准的Runnables。 但是在打电话时

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

PriorityBlockingQueue的比较器接收ASyncTask的Runnable(私有)内部(在源代码中称为mFuture),因此在比较器中我无法识别runnables或读取“priority”值。

我怎么解决这个问题? 谢谢

借用android.os.AsyncTask中的源代码并创建自己的com.company.AsyncTask实现,您可以在自己的代码中控制所需的一切。

android.os.AsyncTask附带两个现成的执行函数,THREAD_POOL_EXECUTOR和SERIAL_EXECUTOR:

 private static final BlockingQueue sPoolWorkQueue = new LinkedBlockingQueue(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并将所有实现包装在这个类中(你对所有内部字段都有可见性),然后使用你的AysncTask:

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

在这里查看我的答案,看看我如何创建自己的AsyncTask以使executeOnExecutor()在API Level 11之前工作。