从线程线程安全调用context.getApplicationContext?

时间:2019-06-16 10:19:57

标签: java android multithreading thread-safety

我编写了以下代码来从数据库中读取一段数据,但是由于该代码从不是UI线程的线程调用c.getApplicationContext,因此我不确定代码是否是线程安全的。 / p>

 public class chat extends AppCompatActivity
{
  protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chat);
        final Context myContext = this;
        AgentAsyncTask zx = new AgentAsyncTask(myContext);
        zx.execute();

        }

 private static class AgentAsyncTask extends AsyncTask<Void, Void, List<Message>> {

        private Context c;
        public AgentAsyncTask(Context c) {
         this.c = c;

        }

        @Override
        protected List<Message> doInBackground(Void... params) {
            List<Message> x = AppDatabase.getAppDatabase(c.getApplicationContext()).userDao().getAll();
            return x;
        }

        @Override
        protected void onPostExecute(List<Message> agentsCount) {
            Toast.makeText(c, agentsCount.get(0).message, Toast.LENGTH_SHORT).show();
        }
    }
}

此代码线程安全吗?我怀疑不是线程安全的行是:

List<Message> x = AppDatabase.getAppDatabase(c.getApplicationContext()).userDao().getAll();

0 个答案:

没有答案