Kasra Kasra - 2 months ago 16
Android Question

Starting/Calling the same thread multiple times Java Android

I need to call the same thread multiple times in my app. Using my original code, the first time is can be executed just fine. But the second time it crashes - I then learned that each thread shall only be executed not more than one time.

My original piece of code:

View.OnClickListener myClickListener = new View.OnClickListener() {

@Override
public void onClick(View v) {
mythread.start();
}
};


Thread mythread = new Thread(){

@Override
public void run() {

runOnUiThread(new Runnable() {
public void run() {
demoBt.setText("Running...");
}
});

try {
sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}

runOnUiThread(new Runnable() {
public void run() {
demoBt.setText("Finished...");
}
});
}
};


So as I said, it crashes if I try to run it for the second time. So I tried modifying it like:

View.OnClickListener myClickListener = new View.OnClickListener() {

@Override
public void onClick(View v) {
test();
}
};

private void test(){

Thread mythread = new Thread(){

@Override
public void run() {

runOnUiThread(new Runnable() {
public void run() {
demoBt.setText("Running...");
}
});

try {
sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}

runOnUiThread(new Runnable() {
public void run() {
demoBt.setText("Finished...");
}
});
}
};

mythread.start();
}


It works very good; but my question is that whether this is the correct way to do this action or there is a more optimal way to do this?

Also, is it an acceptable thing to call a thread from insider of another thread? (like the way I put stuff on UI Thread inside the new thread of mine)

EDIT:
This is just an example. For my actual code I have heavy math-based simulation to be done which takes 10sec to be done. Based on the results that will be shown to the user , they may want to change their input parameters and let the simulation run again. This will happen several times.

Answer

There is nothing bad with that but I think a better way would be using AsyncTask. It is exactly designed for this cases.

You can use AsyncTask multiple times just creating a new one like this new MyAsyncTask().execute(""); (source from here)