以下代码是线程安全的吗?我真的需要设置dataReady
为volatile
,尽管一个线程只有一次写入和多次读取(如下所示的while循环)?
public class MyApplication extends Application
{
/* a flag indicates if the data is fully retrieved from the database */
private volatile boolean dataReady = false;
@Override
public void onCreate()
{
super.onCreate();
new AsyncTask<Void, Void, Void>()
{
@Override
protected Void doInBackground(Void... params)
{
// retrieve data from the database
return null;
}
@Override
protected void onPostExecute(Void result)
{
dataReady = true;
}
}.execute();
}
public boolean isDataReady()
{
return dataReady;
}
}
在其他线程(不是主线程)上:
while(!getApplication().isDataReady()); // wait until the data is ready