How a thread should close itself in Java?
If the run method ends, the thread will end.
If you use a loop, a proper way is like following:
// In your imlemented Runnable class:
private volatile boolean running = true;
public void run()
{
while (running)
{
...
}
}
public void stopRunning()
{
running = false;
}
Of course returning is the best way.
If you want to terminate the thread, then just returning is fine. You do NOT need to call Thread.currentThread().interrupt()
(it will not do anything bad though. It's just that you don't need to.) This is because interrupt()
is basically used to notify the owner of the thread (well, not 100% accurate, but sort of). Because you are the owner of the thread, and you decided to terminate the thread, there is no one to notify, so you don't need to call it.
By the way, why in the first case we need to use currentThread? Is Thread does not refer to the current thread?
Yes, it doesn't. I guess it can be confusing because e.g. Thread.sleep() affects the current thread, but Thread.sleep() is a static method.
If you are NOT the owner of the thread (e.g. if you have not extended Thread
and coded a Runnable
etc.) you should do
Thread.currentThread().interrupt();
return;
This way, whatever code that called your runnable will know the thread is interrupted = (normally) should stop whatever it is doing and terminate. As I said earlier, it is just a mechanism of communication though. The owner might simply ignore the interrupted status and do nothing.. but if you do set the interrupted status, somebody might thank you for that in the future.
For the same reason, you should never do
Catch(InterruptedException ie){
//ignore
}
Because if you do, you are stopping the message there. Instead one should do
Catch(InterruptedException ie){
Thread.currentThread().interrupt();//preserve the message
return;//Stop doing whatever I am doing and terminate
}