【问题标题】:ASyncTask on Executor and PriorityBlockingQueueExecutor 和 PriorityBlockingQueue 上的 ASyncTask
【发布时间】:2012-08-21 06:16:30
【问题描述】:

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

我已经创建了一个带有 PriorityBlockingQueue 的 ThreadPoolExecutor,并且属性比较器适用于标准 Runnables。 但是打电话的时候

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

PriorityBlockingQueue 的 Comparator 接收 ASyncTask 内部的 Runnable(私有)(在源代码中称为 mFuture),因此在比较器中我无法识别可运行对象或读取“优先级”值。

我该如何解决?谢谢

【问题讨论】:

    标签: java android multithreading


    【解决方案1】:

    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 中,创建另一个 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);
    

    查看我的回答 here 并了解我如何创建自己的 AsyncTask 以使 executeOnExecutor() 在 API 级别 11 之前工作。

    【讨论】:

    • 你好。我很想听从这个建议(因为我已经有一个工作的CustomAsyncTask),但我迷失在PRIORITY_THREAD_POOL_EXECUTOR ThreadPoolExecutor 声明中。你能提供一些见解吗?谢谢。
    • @demtex, PRIORITY_THREAD_POOL_EXECUTOR 在官方 AsyncTask API 中不存在,需要您自己在 CustomAsyncTask 中编写。
    • 谢谢,我在这里解释得更好:stackoverflow.com/questions/24461534/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-10
    • 1970-01-01
    • 2010-12-27
    • 2013-05-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多