java - 如何在 Java 中停止正在运行的线程

标签 java multithreading threadpoolexecutor

我正在使用基于 Java 的文件转换工具,该工具可将 PDF 转换为 DOCX,但有时转换会卡住,如果输入文件大小超过 1 MB 并开始使用 100% CPU 和更多内存并继续运行。我想停止这个连续线程。

  1. 我知道 stop() 函数已被弃用。
  2. 调用 thread.interrupt(); 没有帮助,因为线程一直在运行。
  3. 代码中没有循环...所以无法检查循环中的中断标志

如何停止正在运行的线程 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/

相关文章:

java - 找不到生成的 .keystore 文件

java - 比较器如何工作?

java - 使用 WaterMarkExecutor 相对于 ThreadPoolExecutor 有什么优势?

java - 按顺序执行任务但从池中获取线程的 ExecutorService

java - 如何阻止我的程序永远等待? (等待/通知多线程问题)

java - 在 ExecutorService 的 newFixedThreadPool() 中使用队列?

java - 在哪些情况下我们将变量设为公有而将方法设为私有(private)?

java - 如何在 Java 中比较字符串?

android - 如果引用超出范围,为什么 AsyncTask 不会被垃圾回收?

c++ - std::copy_n 中的执行策略的真正含义是什么?