我正在使用基于 Java 的文件转换工具,该工具可将 PDF 转换为 DOCX,但有时转换会卡住,如果输入文件大小超过 1 MB 并开始使用 100% CPU 和更多内存并继续运行。我想停止这个连续线程。
- 我知道
stop()
函数已被弃用。 - 调用
thread.interrupt();
没有帮助,因为线程一直在运行。 - 代码中没有循环...所以无法检查循环中的中断标志
如何停止正在运行的线程 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();
}
}
}
最佳答案
您可以在 boolean
标志的帮助下构建自己的线程终止逻辑。
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();
}
}
这是用例:
RunningThread thread = new RunningThread();
thread.start(); // start the thread
thread.stopThread(); // stops the thread
上述方法最初由 Google 开发人员在一个框架中使用,也就是 Volley
库。
关于java - 如何在 Java 中停止正在运行的线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39683952/