How a thread should close itself in Java?

后端 未结 5 708
傲寒
傲寒 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:16

    If you simply call interrupt(), the thread will not automatically be closed. Instead, the Thread might even continue living, if isInterrupted() is implemented accordingly. The only way to guaranteedly close a thread, as asked for by OP, is

    Thread.currentThread().stop();
    

    Method is deprecated, however.

    Calling return only returns from the current method. This only terminates the thread if you're at its top level.

    Nevertheless, you should work with interrupt() and build your code around it.

提交回复
热议问题