简体   繁体   English

如何在Java中停止正在运行的Thread

[英]How to stop a running Thread in Java

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. 我正在使用基于Java的文件转换工具将PDF转换为DOCX,但有时在转换时它会卡住,如果输入文件大小超过1 MB并开始使用100%CPU和更多内存并继续运行。 I want to stop this continuous thread. 我想停止这个连续的线程。

  1. I know stop() function is deprecated. 我知道不推荐使用stop()函数。
  2. Calling thread.interrupt(); 调用thread.interrupt(); is not helping, since thread is keep running. 没有帮助,因为线程一直在运行。
  3. There is no loop in the code ...so cannot check for interrupted flag in loop 代码中没有循环...因此无法检查循环中的中断标志

How to Stop a running Thread t. 如何停止正在运行的线程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();
        }
    }
}

Thread.interrupt() only sets a flag within the Thread object that the Thread should be interrupted. Thread.interrupt()只在Thread对象中设置一个标志,该标志应该中断Thread。 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. 它不会导致目标Thread抛出InterruptedException ,而是可以被中断的代码必须不断检查该标志以查看是否有人请求它被中断。 That code then must handle it, usually by throwing an InterruptedException . 然后该代码必须处理它,通常是抛出InterruptedException

You can build your own logic in killing the thread by the help of boolean flag. 您可以通过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();
   }

}

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 aka Volley library. 上面的方法最初是谷歌开发人员使用的框架又名Volley库。

Some of the answers say about stopping the loop with volatile boolean isRunning but I do not see any loop in your example. 一些答案说关于使用volatile boolean isRunning停止循环,但我没有在你的例子中看到任何循环。 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. 在你的情况下,我建议关闭你的PDF文件并用一些布尔值标记它 - 然后你可以捕获IOException并且如果设置了标志 - 这意味着你导致了这种情况,你可以完成线程。

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

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM