This is a short question. At some point my thread understand that it should suicide. What is the best way to do it:
- Thread.currentThread().interrupt();
- return;
By the way, why in the first case we need to use currentThread? Is Thread does not refer to the current thread?
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 becauseinterrupt()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.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
Threadand coded aRunnableetc.) you should doThis 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
Because if you do, you are stopping the message there. Instead one should do