OnCreate 中的代码未按顺序 运行

Code in OnCreate isn't being run in order

我没有写我的全部代码,我有以下简单的结构:

public class CreateEventActivity extends ActionBarActivity{
   int x; 
   void onCreate(){
      new AsyncTask1().execute();//here I change the value of x
      Log.i("000000",String.valueOf(x));
   }
   public AsyncTask1 extends AsyncTask<Void, Void ,Void>{
    // process include changing the vlaue of x to 4 
     Log.i("111111",String.valueOf(x));
     }
}

在日志中:标记为 000000 的日志出现在标记为 111111 的日志之前,这是怎么回事?

首先,我认为问题是因为我在 onPostExecute 中链接了 x 的值,所以我在 doInBackground 中这样做了,但问题仍然存在。

这就是异步任务的本质。 异步任务主要用于长时间 运行 操作;例如网络电话、I/O 操作等,因为它们可能需要一段时间。

如果你想在 AsyncTask 完成时有一个回调,你可以覆盖 OnPostExecute() 方法

what's going on?

AsyncTask 是异步的。引用 the documentation:

This class allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers.

您使用 AsyncTask 的原因是在后台线程中进行工作(例如,下载一些数据),然后在主应用程序线程中进行一些工作(例如,更新 UI 基于该数据)。

is there anyway to avoid this?

摆脱 AsyncTask,或了解如何正确使用它。除其他事项外:

  • 如果没有适当的同步逻辑,不要在多个线程中修改相同的数据

  • 不要尝试分叉后台线程,然后阻塞主应用程序线程(这似乎是你想要的),因为这首先消除了后台线程的全部意义

如果您有工作想在 doInBackground() 结束时完成,请将该工作放在 onPostExecute() 中,而不是放在 execute()executeOnExecutor() 调用之后的语句中.