How a thread should close itself in Java?

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

    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.

提交回复
热议问题