AsyncTasks 中的同步方法

Synchronized methods within AsyncTasks

我的应用程序正在从传感器收集数据,我让用户手动保存标签。每当用户触摸按钮以保存标签时,我 运行 一个 AsyncTask 并在 doInBackground 方法内部调用一个同步方法,其唯一目的是将信息保存在文件中。该方法是帮助程序库的一部分,所以我通过静态方法访问它,因此它是一个同步静态方法。我需要按照输入的顺序保存标签。但是,我注意到有时标签以不同的顺序保存,这告诉我同步方法可能无法按预期工作

  1. A​​syncTasks 中的同步方法是否有任何限制?
  2. 有没有更好的方法来完成这个?我的意思是,继续将数据保存在后台线程中,但要确保如果我们有多个线程,我会按照它们到达的顺序执行它们?

代码看起来有点像这样:

public class FileUtil {
    public static synchronized void saveActivityDataToFile() throws IOException{
       //Saving file code
    }
}

//This asynctask is called everytime the user touches the button
private class SaveDataInBackground extends AsyncTask<String, Integer, Void> {

    public SaveDataInBackground(){
    }

    protected Void doInBackground(String... lists) {
        try {
            //I expect this to run on its own thread but synchronously if this asynctask is called multiple times withing a short interval of time
            FileUtil.saveActivityDataToFile();
        }catch (IOException e){
            Log.e(TAG,"Error while saving activity: " + e.getMessage());  
        }
        return null;
    }

    protected void onPostExecute(Void v) {
    }
}
  1. AsyncTasks
  2. 没有对同步方法的任何限制

顺便说一句,同步与顺序无关,它与阻塞 代码的一部分及时仅用于一个线程有关。所以会出现这样的情况:

任务 1 已开始

任务 2 已开始

任务 2 编写并完成

任务 1 编写并完成

  1. 您可以使用 Thread 而不是 AsyncTask。然后只对一个线程使用 ThreadPoolExecutor 或使用 thread.join()

但最好使用 RxJava2Kotlin Coroutines 来处理这些事情