Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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);

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.

How can I solve that? Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
207 views
Welcome To Ask or Share your Answers For Others

1 Answer

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 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();

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);

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...