我正在尝试让一些ASyncTask以优先级同时运行。
我创建了一个带有PriorityBlockingQueue的ThreadPoolExecutor,并且propper比较器适用于标准的Runnables。 但是在打电话时
new Task().executeOnExecutor(threadPool, (Void[]) null);
PriorityBlockingQueue的比较器接收ASyncTask的Runnable(私有)内部(在源代码中称为mFuture),因此在比较器中我无法识别runnables或读取“priority”值。
我该如何解决?感谢
答案 0 :(得分:6)
从android.os.AsyncTask借用源代码并制作您自己的com.company.AsyncTask实现,您可以在自己的代码中控制所需的所有内容。
android.os.AsyncTask附带两个现成的执行函数,THREAD_POOL_EXECUTOR和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 asyncTask = new com.company.AsyncTask();
asyncTask.setPriority(1);
asyncTask.executeOnExecutor(com.company.AsyncTask.PRIORITY_THREAD_POOL_EXECUTOR, (Void[]) null);
查看我的答案here并了解如何创建自己的AsyncTask以使executeOnExecutor()在API Level 11之前正常工作。