Possible Duplicate:
How do you kill a thread in Java?
How to start/stop/restart a thread in Java?
Thread
has the following functions:
destroy()
stop()
suspend()
but they are all deprecated.
What do you use to stop a thread?
You should make sure that it just runs through / exits itself when its supposed to.
Check this for explanation.
You can use a boolean flag to stop the thread. Also you can make use of Thread.isInterrupted() to check if thread was interrupted and ignore the rest of the work same as boolean flag.
class Worker implements Runnable {
private volatile boolean shouldRun = true;
@Override
public void run() {
while (shouldRun) {
// your code here
}
}
public void cancel()
{
shouldRun = false;
}
}
If you wan to know why these functions are deprecated you can check Java Thread Primitive Deprecation
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With