中断java中正常运行的线程

mad*_*dhu 1 java multithreading interrupted-exception

我试图中断正常运行的线程(未处于 sleep() 或 wait() 状态)。

在网络中浏览时,我知道中断正常运行的线程只会将标志设置为 true 并继续该过程。

代码片段是

one.java

......
......
actionperformedmethod {

if (actionCmd.equals("cancel")) {
    try {
        r1.stop();  // to two.java
    } catch (InterruptedException ex) {
        ....
        ....
    }
}
}
Run Code Online (Sandbox Code Playgroud)

two.java

.....
.....
stop method() throws InterruptedException{
        if(!(t.isInterrupted())){
            t.interrupt();
            throw new InterruptedException();
        }
}
Run Code Online (Sandbox Code Playgroud)

从 Two.java 当我抛出 InterruptedException 时,我可以在 one.java 处获取异常块,但是之后如何停止线程,因为即使在该线程似乎继续正常过程之后。

我对线程概念不熟悉,请帮忙..

Ian*_*rts 6

interrupt()方法是合作式的而不是抢占式的——后台任务需要Thread.interrupted()以适当的时间间隔主动检查,并采取行动彻底关闭自己。

public void run() {
  openSomeResources();
  try {
    while(notFinished) {
      if(Thread.interrupted()) return;
      doSomeStuff();
    }
  } finally {
    closeTheResources();
  }
}
Run Code Online (Sandbox Code Playgroud)

在此示例中,如果线程在中间被中断doSomeStuff(),那么它将在响应中断之前完成当前的“迭代”。在一方面迅速响应中断和另一方面仅在执行中的安全点响应之间取得正确的平衡,本质上是特定于特定任务的——没有一刀切的方法——全部回答。

但请注意,任何抛出异常的阻塞方法InterruptedException都会在抛出此异常时重置中断标志。因此,为了使这种检查起作用,每当您收到一个消息时,您必须重新中断自己InterruptedException

try {
  Thread.sleep(3000);
} catch(InterruptedException e) {
  // we were interrupted - set the flag so the next interrupted() check will
  // work correctly.
  Thread.currentThread().interrupt();
}
Run Code Online (Sandbox Code Playgroud)