7 java multithreading android runnable heavy-computation
我的Android应用程序使用了一个特别大的计算,它会使系统崩溃,因为它位于Activity中的UI线程上.我对多线程没什么信心,所以我想得到一些关于如何正确执行的提示.这就是我所拥有的
class ActivtyName extends Activity{
boolean threadcomplete = false;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//stuff
Runnable newthread = new Runnable(){
@Override
public void run() {
doBigComputation();
threadcomplete=true;
}
};
newthread.run();
boolean b = true;
while(b){
if(threadcomplete){
b=false;
startTheApp();
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
现在,我很确定我做的不是"正确".(它似乎工作.这个系统不会崩溃).基本上,我不确定如何在没有此布尔值,threadcomplete的情况下告知UI线程newthread已完成计算.有没有"正确"的方法来做到这一点?
Mar*_*nto 12
只是为了扩展Marek Sebera的评论,这里是关于如何在AsyncTask中实现这一目标的框架.
private class BigComputationTask extends AsyncTask<Void, Void, Void> {
@Override
protected void onPreExecute() {
// Runs on UI thread
Log.d(TAG, "About to start...");
}
@Override
protected Void doInBackground(Void... params) {
// Runs on the background thread
doBigComputation();
}
@Override
protected void onPostExecute(Void res) {
// Runs on the UI thread
Log.d(TAG, "Big computation finished");
startTheApp();
}
}
Run Code Online (Sandbox Code Playgroud)
并称之为:
BigComputationTask t = new BigComputationTask();
t.execute();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4224 次 |
| 最近记录: |