How a thread should close itself in Java?

后端 未结 5 711
傲寒
傲寒 2020-12-12 15:57

This is a short question. At some point my thread understand that it should suicide. What is the best way to do it:

  1. Thread.currentThread().interrupt();
5条回答
  •  不思量自难忘°
    2020-12-12 16:26

    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
    }
    

提交回复
热议问题