如何确保所有的语句被执行? [英] How to make sure all statements are executed?
问题描述
如何确保在doInBackground线程()方法已经完成或不?
我要完成我在doInBackground(已经开始的线程)方法postExecute被调用之前。
how to make sure that the thread in doInBackground() method has been completed or not ? I want to finish the thread which I have started in doInBackground() method before postExecute gets called.
package com.application.test;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
public class MyActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
new MyTask().execute(null);
}
private class MyTask extends AsyncTask<Void, Void, Void>
{
protected static final String TAG = "Async";
@Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
new Thread(new Runnable(){
@Override
public void run() {
// TODO Auto-generated method stub
for (int i = 0; i < 200; i++) {
Log.e(TAG, ""+i);
}
}
}).start();
return null;
}
@Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
Log.e(TAG, "Post execute");
}
}
}
我要确保线程仅在doInBackground方法来完成。
I want to make sure that thread has to complete in doInBackground method only.
推荐答案
的问题是,你从里面doInbackground()创建一个新的线程。
The problem is that you are creating a new thread from inside doInbackground().
不要到一般,请勿混用线程和AsyncTask的。更改code到
Don't to that and generally, don't mix Thread and AsyncTask. Change your code to
@Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
for (int i = 0; i < 200; i++) {
Log.e(TAG, ""+i);
}
return null;
}
这将确保在doInBackground()所有code有onPostExecute()之前完成被调用。
This will make sure that all code in doInBackground() has finished before onPostExecute() is called.
这篇关于如何确保所有的语句被执行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!