如何在没有任何用处的情况下停止永远运行的线程 [英] How to stop a thread that is running forever without any use

查看:84
本文介绍了如何在没有任何用处的情况下停止永远运行的线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In the below code, i have a while(true) loop. considering a situation where there is some code in the try block where the thread is supposed to perform some tasks which takes about a minute, but due to some expected problem, it is running for ever. can we stop that thread ?

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();
            }
        }
    }
}


推荐答案

首先,你没有在这里开始任何线程!你应该创建一个新的线程,并将令人困惑的名为 thread1 Runnable 传递给它:

First of all, you are not starting any thread here! You should create a new thread and pass your confusingly named thread1 Runnable to it:

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

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

Now, when you really have a thread, there is a built in feature to interrupt running threads, called... interrupt():

thread.interrupt();

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

However, setting this flag alone does nothing, you have to handle this in your running thread:

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();
    }

有两点需要注意: isInterrupted()时,$ c>循环现在将结束。但是如果线程在睡眠期间被中断,那么JVM是如此善意,它会通过抛出中断的异常来告诉你 sleep()。抓住它并打破你的循环。就是这样!

Two things to note: while loop will now end when thread isInterrupted(). But if the thread is interrupted during sleep, JVM is so kind it will inform you about by throwing InterruptedException out of sleep(). Catch it and break your loop. That's it!

至于其他建议:

  • About Thread.stop():

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

Deprecated. This method is inherently unsafe[...]




  • 添加自己的旗帜并密切关注它很好(只记得使用 AtomicBoolean volatile !),但是为什么JDK已经为你提供了一个内置的...在这样的国旗?额外的好处是中断 sleep s,使线程中断更具响应性。

    • Adding your own flag and keeping an eye on it is fine (just remember to use AtomicBoolean or volatile!), but why bother if JDK already provides you a built-in flag like this? The added benefit is interrupting sleeps, making thread interruption more responsive.
    • 这篇关于如何在没有任何用处的情况下停止永远运行的线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆