I want to write a code with threads to make a concurrent app. when I click on "Main Thread" button the "doHeavyWork" method starts and show a toast to user when it's finish!
but when I want to use threads and click on "Single Thread" button, the "doHeavyWork" method starts, but at last the program stops and crash.
what is my problem?
I use a physical phone to debug.
these is my code:
package khosravi.mehdi.course.app.thread_test;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Toast;
public class MyTestThreadActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
findViewById(R.id.btnMainThread).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
doHeavyWork();
}
});
findViewById(R.id.btnSingleThread).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
doHeavyWork();
}
});
thread.start();
}
});
}
public void doHeavyWork() {
String str = "";
for (int i = 0; i < 7000; i++) {
str += i;
Log.i("LOG", "i:" + i);
}
Toast.makeText(MyTestThreadActivity.this, "Heavy Work is finish !", Toast.LENGTH_SHORT).show();
}
}