Asynctask不是按照AsyncTask.SERIAL_EXECUTOR顺序执行
创始人
2024-09-21 09:30:49
0

AsyncTask的执行顺序可以通过使用自定义的Executor来解决。以下是一个示例代码,展示了如何使用自定义的Executor来确保AsyncTask按照AsyncTask.SERIAL_EXECUTOR顺序执行。

首先,我们需要创建一个自定义的Executor,用于按照顺序执行AsyncTask。代码如下:

import java.util.concurrent.Executor;

public class SerialExecutor implements Executor {
    private final ArrayDeque tasks = new ArrayDeque<>();
    private Runnable active;

    @Override
    public synchronized void execute(final Runnable r) {
        tasks.offer(new Runnable() {
            public void run() {
                try {
                    r.run();
                } finally {
                    scheduleNext();
                }
            }
        });
        if (active == null) {
            scheduleNext();
        }
    }

    protected synchronized void scheduleNext() {
        if ((active = tasks.poll()) != null) {
            AsyncTask.THREAD_POOL_EXECUTOR.execute(active);
        }
    }
}

接下来,我们可以在AsyncTask的executeOnExecutor()方法中使用这个自定义的Executor来确保按顺序执行。示例代码如下:

MyAsyncTask task1 = new MyAsyncTask();
MyAsyncTask task2 = new MyAsyncTask();
MyAsyncTask task3 = new MyAsyncTask();

// 使用自定义的Executor来确保按顺序执行
task1.executeOnExecutor(new SerialExecutor());
task2.executeOnExecutor(new SerialExecutor());
task3.executeOnExecutor(new SerialExecutor());

这样,task1、task2和task3将会按照顺序执行,而不会出现并发执行的情况。

注意:需要确保在Android 4.0及以上版本中使用executeOnExecutor()方法,而不是execute()方法来执行AsyncTask,以便能够指定自定义的Executor。在Android 4.0以下版本中,默认采用的是AsyncTask.SERIAL_EXECUTOR来执行AsyncTask。

相关内容

热门资讯

9分钟辅助!wepoker辅助... 9分钟辅助!wepoker辅助是真的假的,wpk控制牌是真的吗,方式教程(揭秘有挂)1、完成wepo...
一分钟辅助!pokemmo脚本... 一分钟辅助!pokemmo脚本手机版,aapoker怎么提高中牌率,阶段教程(有挂解密)暗藏猫腻,小...
四分钟辅助!we-poker有... 四分钟辅助!we-poker有人玩吗,wepoker免费脚本咨询,演示教程(有挂教程)wepoker...
八分钟辅助!aa poker辅... 八分钟辅助!aa poker辅助,pokemmo内置修改器,方式教程(证实有挂)1、完成pokemm...
第2分钟辅助!智星菠萝透视,h... 第2分钟辅助!智星菠萝透视,hhpoker到底可以作弊码,策略教程(有挂规律)1、hhpoker到底...
第1分钟辅助!wepoker怎... 第1分钟辅助!wepoker怎么发冤家牌,pokemomo辅助软件,办法教程(有挂解惑)1、wepo...
第1分钟辅助!德普之星辅助工具... 第1分钟辅助!德普之星辅助工具如何打开,德州局hhpoker,总结教程(有挂辅助)1、进入游戏-大厅...
第九分钟辅助!wepoker私... 第九分钟辅助!wepoker私人局俱乐部,德州圈脚本,妙招教程(有挂分享)暗藏猫腻,小编详细说明we...
第四分钟辅助!wpk模拟器,h... 第四分钟辅助!wpk模拟器,hhpoker辅助靠谱吗,技法教程(有挂讲解)1、完成hhpoker辅助...
第十分钟辅助!wepoker轻... 第十分钟辅助!wepoker轻量版辅助,wpk德州局透视,模板教程(有挂方针)wepoker轻量版辅...