如何在 Java 中停止正在运行的线程
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39683952/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to stop a running Thread in Java
提问by shirish sahu
I am using a Java based file conversion tool which converts PDF to DOCX, but sometimes while conversion it stuck, if input file size is more then 1 MB and start utilizing 100% CPU and more memory and keep running. I want to stop this continuous thread.
我正在使用基于 Java 的文件转换工具将 PDF 转换为 DOCX,但有时在转换时它会卡住,如果输入文件大小超过 1 MB 并开始使用 100% CPU 和更多内存并继续运行。我想停止这个连续的线程。
- I know
stop()
function is deprecated. - Calling
thread.interrupt();
is not helping, since thread is keep running. - There is no loop in the code ...so cannot check for interrupted flag in loop
- 我知道
stop()
功能已被弃用。 - 调用
thread.interrupt();
没有帮助,因为线程一直在运行。 - 代码中没有循环......因此无法检查循环中的中断标志
How to Stop a running Thread t.
如何停止正在运行的线程
public class ThreadDemo implements Runnable {
Thread t;
PdfToDocConversion objPdfToDocConversion;
ThreadDemo() throws InterruptedException {
t = new Thread(this);
System.out.println("Executing " + t.getName());
// this will call run() fucntion
t.start();
Thread.sleep(2000);
// interrupt the threads
if (!t.interrupted()) {
System.out.println("Interrupted");
t.interrupt();
}
System.out.println(t.isInterrupted()); // true
System.out.println(t.getName());
System.out.println(t.isAlive()); /// still true
// block until other threads finish
try {
t.join();
} catch (InterruptedException e) {
}
}
public void run() {
objPdfToDocConversion = new PdfToDocConversion();
try {
objPdfToDocConversion.convertDocToPdf();//inside this function thread got stuck
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
System.out.print(t.getName() + " interrupted:");
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String args[]) {
try {
new ThreadDemo();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
回答by Smith_61
Thread.interrupt()
only sets a flag within the Thread object that the Thread should be interrupted. It does not cause the target Thread to throw an InterruptedException
, instead code that can be interrupted must continually check that flag to see if someone has requested it be interrupted. That code then must handle it, usually by throwing an InterruptedException
.
Thread.interrupt()
只在 Thread 对象中设置一个标志,表明 Thread 应该被中断。它不会导致目标线程抛出InterruptedException
,而是可以被中断的代码必须不断检查该标志以查看是否有人请求将其中断。然后该代码必须处理它,通常是通过抛出InterruptedException
.
回答by Enzokie
You can build your own logic in killing the thread by the help of boolean
flag.
您可以在boolean
flag的帮助下构建自己的杀死线程的逻辑。
public class RunningThread implements Thread {
private volatile boolean running = true;
public void run() {
while (running) {
try {
// Add your code here
} catch (InterruptedException e) {
if(!running){
break;
}
}
}
}
public void stopThread() {
running = false;
interrupt();
}
}
Here is the usecase:
这是用例:
RunningThread thread = new RunningThread();
thread.start(); // start the thread
thread.stopThread(); // stops the thread
The approach above is originally used by Google developers in on of there framework a.k.a Volley
library.
上面的方法最初是由 Google 开发人员在框架(又名Volley
库)中使用的。
回答by Wojciech Kazior
Some of the answers say about stopping the loop with volatile boolean isRunning
but I do not see any loop in your example. Interrupting the thread does not actually interrupt it "right now". It just says "thread will be interrupted as soon as there will be such an opportunity". In your case I would suggest to close your PDF file and flag it with some boolean - then you can catch the IOException and if the flag is set - it means that you caused this situation and you can finish the thread.
一些答案说关于停止循环,volatile boolean isRunning
但我在你的例子中没有看到任何循环。中断线程实际上并没有“立即”中断它。它只是说“一旦有这样的机会,线程就会被中断”。在你的情况下,我建议关闭你的 PDF 文件并用一些布尔值标记它 - 然后你可以捕获 IOException 并且如果设置了标志 - 这意味着你导致了这种情况并且你可以完成线程。
回答by F4Code.com
You can create a boolean field and check it inside run:
您可以创建一个布尔字段并在运行中检查它:
public class Task implements Runnable {
private volatile boolean isRunning = true;
public void run() {
while (isRunning) {
//do work
}
}
public void kill() {
isRunning = false;
}
}