Java Thread.stop() 与 Thread.interrupt()

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20527893/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 02:33:33  来源:igfitidea点击:

Java Thread.stop() vs Thread.interrupt()

javamultithreading

提问by ágota Horváth

I have the following code:

我有以下代码:

renderThread = new Thread(new Runnable() {

    @Override
    public void run() {
        for (int i = 0; i < 10000000; i++) {
            System.out.println("Number: " + i);
        }
    }
});

renderThread.start();

try {
    Thread.sleep(100);
} catch (InterruptedException ex) {
    ex.printStackTrace();
}

renderThread.interrupt(); //It should stop, but it does not stop.

renderThread.interrupt()does not interrupt the thread, it continues to run. If I replace renderThread.interrupt()with .stop(), then the thread stops. However, .stop()is deprecated. Then, what is the proper way of stopping a thread, if stopis deprecated and interruptdoes not work?

renderThread.interrupt()不中断线程,它继续运行。如果我替换renderThread.interrupt().stop(),则线程停止。但是,.stop()已弃用。那么,如果stop不推荐使用并且interrupt不起作用,停止线程的正确方法是什么?

回答by brunch875

You should take a look at this article: http://10kloc.wordpress.com/2013/03/03/java-multithreading-steeplechase-stopping-threads/

你应该看看这篇文章:http: //10kloc.wordpress.com/2013/03/03/java-multithreading-steeplechase-stopping-threads/

Basically you shouldn't STOP a thread (unsafe), but interrupt it. What you're missing is making the thread handle the interruption.

基本上你不应该停止一个线程(不安全),而是中断它。您缺少的是让线程处理中断。

回答by csn

interrupt() method does not stop the Thread. read this for more detailed explanation http://www.ibm.com/developerworks/java/library/j-jtp05236/

中断()方法不会停止线程。阅读本文以获得更详细的解释http://www.ibm.com/developerworks/java/library/j-jtp05236/

回答by chasep255

When you call interrupt() it triggers a boolean flag which tells the run function it should stop. That is why I usually write my run functions like this.

当您调用 interrupt() 时,它会触发一个布尔标志,告诉运行函数它应该停止。这就是为什么我通常像这样编写我的运行函数。

void run()
{
    while(!Thread.interrupted())
    {
        //Do something
    }
}

Just because you call interrupt doesn't mean the thread will stop immediately or at all. It depends on what is in the run function.

仅仅因为您调用中断并不意味着线程会立即停止或根本停止。这取决于运行函数中的内容。

回答by John Vint

To really push the point why you shouldnt use Thread.stop()?

真正强调为什么不应该使用Thread.stop()?

Doug Lea recently mentioned that Thread.stop will be the first de-implemented method for Javacome Java 8.

Doug Lea 最近提到 Thread.stop 将是Java 8 中第一个取消实现的方法

His response to this comment from someone:

他对某人评论的回应:

Also, one other thing synchronized has going for it is it handles async aborts of threads (I.e. thread.stop()). I know stop() is deprecated and all, but you never know.

此外,同步的另一件事是它处理线程的异步中止(即 thread.stop())。我知道 stop() 已被弃用,但您永远不知道。

Was:

曾是:

But you do know! As of JDK8, Thread.stop is really gone. It is the first deprecated method to have actually been de-implemented. It now just throws UnsupportedOperationException.

但你知道!从 JDK8 开始,Thread.stop 真的消失了。这是第一个实际上已被取消实现的弃用方法。它现在只是抛出 UnsupportedOperationException。

http://cs.oswego.edu/pipermail/concurrency-interest/2013-December/012028.html

http://cs.oswego.edu/pipermail/concurrency-interest/2013-December/012028.html

回答by Sage

renderThread.interrupt() does not interrupt the thread, it continues to run.

renderThread.interrupt() 不会中断线程,它会继续运行。

  • If the thread is executing and interrupt()is invoked it's interrupt status is set.
  • If this thread is blocked in an invocation one of waitmethods of the Object class, or of the Thread.joinand Thread.sleepmethods of this class then its interrupt status will be clearedand it will receive an InterruptedException.
  • 如果线程正在执行并被interrupt()调用,则设置其中断状态。
  • 如果此线程wait在 Object 类的方法之一或此类的Thread.joinThread.sleep方法的调用中被阻塞, 则其中断状态将被清除,并且它会收到一个InterruptedException.

For example:

例如:

Thread t = new Thread()
      {
          public void run()
          {
              try {
                  for(int i=0; i<10000;i++)
                      System.out.println("Is interrupTed? "+this.isInterrupted());

                  Thread.sleep(200);
              } catch (InterruptedException ex) {
                  Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
              }

          }
      };
      t.start();
      t.interrupt();
    }

The above code, I have used a forloop to intercept the interrput flag with isInterrupted()function and printed it. As t.interrupt()is invoked, isInterrupted()will return truewhich you will see in the console. As soon as it reaches the Thread.sleep(miliTime)you will see that InterruptedExceptionis caught which was thrown as described above.

上面的代码,我使用了一个for循环来拦截带有isInterrupted()函数的interrput标志并打印出来。作为t.interrupt()被调用时,isInterrupted()将返回true您将在控制台中看到。一旦它到达 ,Thread.sleep(miliTime)您就会看到InterruptedException被捕获的,如上所述被抛出。

Stopping a thread:

停止线程:

you could make use of this isInterrupted()flag check if an interrupt()was invoked on it and return from the execution:

您可以使用此isInterrupted()标志检查是否interrupt()在其上调用了an并从执行中返回:

For example:

例如:

Thread t = new Thread()
      {
          public void run()
          {
              long executeTime = System.currentTimeMillis() ;
              int i = 0;    
              for(; i<10000 && !this.isInterrupted();i++)
                      System.out.println("Is interrupted? "+this.isInterrupted());

               System.out.println("Was Interrupted? "+this.isInterrupted()
                                  +" after cycle: "+ i);
               System.out.println("Time it gets Executed: "
                                  +(System.currentTimeMillis() - executeTime+" ms"));

          }
      };
      t.start();
        try {
            Thread.sleep(200);
        } catch (InterruptedException ex) {
            ex.printStackTrace();
        }
      t.interrupt();

While running the above code: i have sent the main thread to sleep for 200inside the static main function to allow the started thread tto run for some time. Then i invoked
t.interrupt()on it which causes the forloop to stop and print a output as following:

在运行上面的代码时:我已将主线程发送到200静态主函数内部以允许启动的线程t运行一段时间。然后我调用
t.interrupt()它导致for循环停止并打印如下输出:

Was Interrupted? true after cycle: 1477
Time it gets Executed: 258 ms

Which indicates that the forloop has 1148iteration before t.interrupt();was invoked in the mainfunction.

这表明for循环在函数中被调用1148之前有迭代。t.interrupt();main

Please read the documentation of Thread.interrupt()function for more details.

请阅读Thread.interrupt()函数文档以获取更多详细信息。

回答by Paul Okeke

All You need do to interrupt the current thread or terminate the running process of the thread is to add the below statement within you catch block

中断当前线程或终止线程的运行过程所需要做的就是在 catch 块中添加以下语句

try
{
   Thread.sleep(4000);
   System.out.println("VAS CONSULTING")
}
catch(InterruptedException e)
{
   //Stop printing out VAS CONSULTING
   return;  /*This will terminate the thread*/
}

also if a method that doesn't throw an Interrupted Exception isn't used within the run method you can do this to handle Thread Interruption or terminate the Thread

此外,如果在 run 方法中未使用不引发中断异常的方法,您可以执行此操作来处理线程中断或终止线程

@Override
public void run()
{

   System.out.println("VAS CONSULTING");
   if(Thread.Interrupted())
   {
     doSomethingElse();//process something else within the thread
    return; //Terminates the current Thread
   }

}

I hope this Helps You or Someone Else.

我希望这对您或其他人有帮助。