How to stop a task that is running?
You should make your thread support interrupts. How does a thread support its own interruption? This depends on what it's currently doing.
join() to wait thread to die, and set a abort flag
public void stopParse() {
try {
if (mParseThread != null) {
mIsAbort = true;
mParseThread.join();
mParseThread = null;
}
// do clean stuff
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private class ParseThread extends Thread {
@Override
public void run() {
while (!mIsAbort) {
}
}
}
throw InterruptedException
If the thread is frequently invoking methods that throw InterruptedException, it simply returns from the run method after it catches that exception:
for (int i = 0; i < importantInfo.length; i++) {
// Pause for 4 seconds
try {
Thread.sleep(4000);
} catch (InterruptedException e) {
// We've been interrupted: no more messages.
return;
}
// Print a message
System.out.println(importantInfo[i]);
}
Many methods that throw InterruptedException
, such as sleep, are designed to cancel their current operation and return immediately when an interrupt is received.
periodically check Thread.interrupted()
What if a thread goes a long time without invoking a method that throws InterruptedException? Then it must periodically invoke Thread.interrupted, which returns true if an interrupt has been received.
Basically, you can call yourThread.interrupt()
to stop the thread and, in your run() method you'd need to periodically check the status of Thread.interrupted().
for (int i = 0; i < inputs.length; i++) {
heavyCrunch(inputs[i]);
if (Thread.interrupted()) {
// We've been interrupted: no more crunching.
return;
}
}