java - 如何停止一个永远运行而没有任何用处的线程

标签 java multithreading

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


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 传递给它:

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

需要注意两点:while 循环现在将在线程 isInterrupted() 时结束。但是如果线程在 sleep 期间被中断,JVM 非常友好,它会通过从 sleep() 中抛出 InterruptedException 来通知您。捕获它并打破你的循环。就是这样!


至于其他建议:

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

  • 添加您自己的标志并密切关注它很好(只要记住使用 AtomicBooleanvolatile!),但如果 JDK 已经为您提供了内置-in 像这样的标志?额外的好处是中断 sleeps,使线程中断更具响应性。

关于java - 如何停止一个永远运行而没有任何用处的线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6410721/

相关文章:

java - 在 Java 中使用逗号和 "and"连接列表<String>

java - 类似python的Java IO库?

c# - 在实现生产者/消费者模式时使用 Task.Yield 克服 ThreadPool 饥饿

java - 使用来自同一类的两个线程(偶数和奇数)打印 1-1000

java - 如何将 "&nbsp;"表示为 Scanner 的分隔符

java - 有没有办法限制 Hibernate envers 的审计日志量?

java - 我可以使用 java 在后台捕获键盘和鼠标事件吗?

multithreading - 如何在 Node.js 应用程序中使用 Apache OpenNLP

java - 服务时间与线程数成正比

c# - 如何构建类似于 TransactionScope 的类