Reputation: 12269
Is there a way to check if a Thread object has had start called on it already?
I'm trying to so something like:
if(rt.isAlive() == true)
{
Log.v(TAG, "START RECORD");
rt.recording = true;
}
else
{
Log.v(TAG, "START THREAD/RECORD");
rt.start();
}
where it would start the thread if it's not already running.
Upvotes: 14
Views: 43049
Reputation: 62519
I've used this approach with success:
if ( mythread.getState() == Thread.State.NEW )
//then we have a brand new thread not started yet, lets start it
mythread.start();
else
//it is running already compensate
Upvotes: 7
Reputation: 1388
Call this method by passing a thread. It will check the thread is alive or not, every 500 milliseconds with start delay of 500 milliseconds (you can use your custom values). I use this method often.
void threadAliveChecker(final Thread thread) {
final Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
if (!thread.isAlive()) {
// do your work after thread finish
runOnUiThread(new Runnable() {
@Override
public void run() {
// do the ui work here
}
});
timer.cancel();
}else {
// do work when thread is running like show progress bar
}
}
}, 500, 500); // first is delay, second is period
}
Example:
Thread thread = new Thread(myRunnable);
thread.start();
threadIsAliveChecker(thread);
This method will let us know when the thread is finished doing its work.
Upvotes: 0
Reputation: 77722
Assuming that rt
is a Thread
, just check rt.isAlive()
.
Alternatively, just use a boolean flag and set it to true right before you start your thread.
I would actually prefer the boolean approach so there is no way that the main thread could start the other thread twice - there may be a short delay until your Thread is up and running, and if your main thread tries to start the thread twice in quick succession, it may get a "false" negative on rt.isAlive()
.
Upvotes: 15
Reputation: 13554
If you called start on it, and it is running, you will get an IllegalThreadStateException
. Catching that is one way to know.
Another option is to extend Thread and add a boolean where you keep track of whether or not your Thread has been started. You can override the start method of Thread to check the boolean before calling up to super.start()
.
You should be very careful when using threads in Android though. Make sure you understand the lifecycle of the component that is starting it. Also, you should consider some of the helper classes like Handler and AsyncTask instead of directly spawning threads.
Upvotes: 2