如何停止在没有任何使用的情况下永久运行的线程

2022-09-01 20:00:28

在下面的代码中,我有一个 while(true) 循环。考虑到在try块中有一些代码的情况,其中线程应该执行一些任务,大约需要一分钟,但由于一些预期的问题,它永远在运行。我们可以停止那个线程吗?


public class thread1 implements Runnable {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        thread1 t1 = new thread1();
        t1.run();

    }

    @Override
    public void run() {
        // TODO Auto-generated method stub
        while(true){
            try{        
                Thread.sleep(10);

            }
            catch(Exception e){
                e.printStackTrace();
            }
        }
    }
}

答案 1

首先,您不会在这里启动任何线程!你应该创建一个新线程,并将你令人困惑的名字传递给它:thread1Runnable

thread1 t1 = new thread1();
final Thread thread = new Thread(t1);
thread.start();

现在,当你真的有一个线程时,有一个内置的功能来中断正在运行的线程,称为...:interrupt()

thread.interrupt();

但是,单独设置此标志不会执行任何操作,您必须在正在运行的线程中处理此问题:

while(!Thread.currentThread().isInterrupted()){
    try{        
        Thread.sleep(10);
    }
    catch(InterruptedException e){
        Thread.currentThread().interrupt();
        break; //optional, since the while loop conditional should detect the interrupted state
    }
    catch(Exception e){
        e.printStackTrace();
    }

需要注意的两件事:当线程时,循环现在将结束。但是,如果线程在睡眠期间中断,JVM非常友善,它会通过抛出.抓住它,打破你的循环。就是这样!whileisInterrupted()InterruptedExceptionsleep()


至于其他建议:

已弃用。这种方法本质上是不安全的[...]

  • 添加自己的标志并密切关注它是可以的(只要记住使用或!),但是如果JDK已经为您提供了这样的内置标志,为什么还要打扰呢?额外的好处是中断s,使线程中断的响应速度更快。AtomicBooleanvolatilesleep

答案 2

停止线程的正确方法是它(已弃用,可能会产生令人讨厌的副作用):interruptstop()

t1.interrupt()

这将导致 由 or 等方法引发 。InterruptedExceptionThread.sleep()Object.wait()

然后只需为此异常添加一个 catch 块,然后直接退出循环。breakwhile

编辑:我现在意识到你的无限循环正在主线程内运行,你的代码没有创建线程,它只是在运行一个.您需要在某个时候调用以生成新线程。run()RunnableThread.start()