为什么我的 interrupt() 方法没有终止我的线程?

huangapple go评论109阅读模式
英文:

Why did my interrupt() not kill my thread?

问题

我在AEM中有一个名为helper的Java类代码片段如下

public class Helper extends Thread {
    // ................
    private String glossaryText;

    public String getGlossaryText() {
        Thread thread = new Thread() {
            public void run() {
                glossaryText = getGlossaryHTML();
            }
        };
        try {
            thread.start();
        } catch (Exception e) {

        } finally {
            // 这并不会停止线程
            thread.interrupt();
        }
        System.out.println(thread.isAlive());
        return glossaryText;
    }
    // ........
}
问题是无论我做什么**System.out.println(thread.isAlive());** 总是打印出true”。**thread.interrupt();** 并没有停止线程
英文:

I have a Java class in AEM called "helper", the snippet looks like this:

public class Helper extends Thread{
    ................
      private String glossaryText;
      public String getGlossaryText() {
           Thread thread = new Thread() {
              public void run() {
                  glossaryText = getGlossaryHTML();
            }
        };
        try {
           thread.start();
        }
        catch(Exception e) {
        
        }finally {
           //this does NOT stop the thread
         thread.interrupt(); 
        }
        System.out.println(thread.isAlive());
        return glossaryText;
   }
 ........
 }

The problem is that, no matter what i do, System.out.println(thread.isAlive()); always print "true". thread.interrupt(); did not stop the thread.

答案1

得分: 1

interrupt()并不能立即停止线程。它只是向线程发出的一个信号,告诉线程它应该尽快停止。你必须自己构建对这个信号的响应。

问题在于,你没有等待线程结束。你只是启动线程,发出停止信号,然后检查它是否还在运行。在thread.start()和你的打印之间,有很小的机会线程会被执行,但在大多数情况下,执行线程将会在处理getGlossaryText()后结束。

你可以在打印语句前面加上thread.join(500);,这样你的线程就不会再存活,因为它会等待线程执行完毕。

英文:

interrupt() does not work instantly stop the thread. It is just a signal to the thread, that it should stop itself soon. You have to build an reaction to it yourself.

The thing is, you don't wait for your thread to end. You just start the thread, signal it to stop an then check if its alive. There is a really small chance that between thread.start() and your print the thread will be executed, but in most cases the executing thread will just end processing getGlossaryText().

You could just put a thread.join(500); in front of your print and then your thread won't be alive anymore because it waits for the thread to be executed.

huangapple
  • 本文由 发表于 2020年9月22日 22:54:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/64012349.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定