小编典典

如何在Java中停止不间断线程

java

我有一个Java应用程序, 我不能编辑 启动一个java.lang.Thread具有此run()方法:

public void run(){
   while(true){
     System.out.println("Something");
   }
}

我想在某个时间点停止它。如果我使用Thread.interrupt()它不起作用。如果我使用Thread.stop()它,则可以使用,但是不建议使用此方法(因此不建议使用该方法,因为在新版本中可能会将其从JVM中删除)。

如何在Java中停止此类不间断线程?


阅读 264

收藏
2020-09-26

共1个答案

小编典典

您可以使用检查变量来实现中断方法。

首先,使用易失性检查变量作为:

volatile boolean tostop = false; // Keep the initial value to be false

接下来,将您的线程定义为依赖于此变量。

Thread thread1 = new Thread(){
    public void run() {
        while(!tostop) {
         -- Write your code here --
        }
     }
 }

接下来定义在其中使用线程的函数:

public void ....{
    //Interrupt code
    tostop = true;
    thread1.sleep(300);  // Give the thread sometime for cleanup
    //Use System.exit(0), if the thread is in main function.
}

希望这可以帮助。

2020-09-26