如何在java线程运行时中断或杀死它。

问题描述 投票:0回答:1

看了几篇SO的帖子,关于如何杀死一个Java线程,我相当理解为什么stop是 不安全 以及如何处理优雅的停止。

但这些解决方案是针对UI线程的,其中重绘是问题,而不是真正的长期运行--由线程执行的阻塞进程。

链接

如何在Java中杀死一个线程?https:/docs.oracle.comjavase1.5.0docsguidemiscthreadPrimitiveDeprecation.html

从解决方案或例子中,我无法理解的一个精确点是,样本试图模拟的长期运行部分是什么。

例如:在下面这段代码中,如果我把时间间隔设置为INT.MAX.A,会怎么样?

public void run() {
        Thread thisThread = Thread.currentThread();
        while (blinker == thisThread) {
            try {
                thisThread.sleep(interval);  // This might take forever to complete, 
                                             // and while may never be executed 2nd time.

                synchronized(this) {
                    while (threadSuspended && blinker==thisThread)
                        wait();
                }
            } catch (InterruptedException e){
            }
            repaint();
        }
    }

    public synchronized void stop() {
        blinker = null;
        notify();
    }

我问这个用例的原因是,我有一个遗留代码库的bug,在一个Thread中运行另一个可执行文件,现在问如果用户希望停止这个线程,我们需要杀死这个线程,作为这个线程一部分的可执行文件会自动被杀死。

java multithreading thread-safety java-threads legacy
1个回答
2
投票

你停止线程的方法是要求它--很好地--停止。线程正在运行的代码要监听并执行这个请求。

具体来说,你的方法是中断线程。你的代码检查中断------。Thread.sleepObject.wait 会扔 InterruptedException 如果线程在执行前或执行过程中被中断,但你抓住了中断,并忽略了它,所以你不会对它采取行动。

而不是这样。

while (condition) {
  try {
    Thread.sleep(...);

    wait();
  } catch (InterruptedException e) {
  }
}

把中断放在循环之外:

try {
  while (condition) {
    Thread.sleep(...);
    wait();
  }
} catch (InterruptedException e) {
}

如果线程被打断,循环就会终止。

© www.soinside.com 2019 - 2024. All rights reserved.