ASyncTask on Executor and PriorityBlockingQueue

后端 未结 1 1959
旧时难觅i
旧时难觅i 2020-12-06 14:27

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

I\'ve creating a ThreadPoolExecutor with an PriorityBlockingQueue and the propper comparat

相关标签:
1条回答
  • 2020-12-06 15:06

    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.

    0 讨论(0)
提交回复
热议问题