java - 该程序中中断的执行顺序是如何工作的?

标签 java multithreading interrupt

我正在阅读Java中中断的实现,但我无法弄清楚控制是如何流动的?

代码片段是:

public class Main implements Runnable
{

 Thread t;

 Main() 
{
  t = new Thread(this);
  t.start();
  t.interrupt();  
  if (!t.interrupted())
  {
  System.out.println("TRUE");
  }
}

 public void run() 
 {
  try 
  {   
   System.out.println("Thread is in running state");
   Thread.sleep(1000);

  } 
  catch (InterruptedException e) 
  {
   System.out.print(t.getName() + " interrupted");
  }
 }

 public static void main(String args[]) 
{
  new Main();
 }
}

根据我的理解,通过查看构造函数中的执行顺序应该是:

Thread is in running state
Thread-0 interrupted
TRUE

但这是错误的。

正确的输出是:

TRUE
Thread is in running state
Thread-0 interrupted

那么请解释一下这个执行顺序是如何工作的以及为什么?

<小时/>

编辑 1: 正如指出的那样,调用 t.interrrrupted() 会产生误导,因此我将构造函数更改为:

 Main() 
{
  t = new Thread(this);
  t.start();
  t.interrupt();  
  if (!Thread.interrupted())
  {
  System.out.println("TRUE");
  }
}

所以现在的输出是:

TRUE
Thread is in running state
Thread-0 interrupted

现在的问题是,

  1. Since the thread is in the non-runnable state when t.interrupt() was called, then what does t.interrupt() do in that case?
  2. Why the last line of output is printed? From where does it get interrupt, because t.interrupt was executed when the thread was in the non-runnable state.

最佳答案

首先,您调用了错误的方法。

正如另一个答案中所指出的,interrupted() 是一个静态方法,它始终检查当前线程的中断状态。如果您想检查t的状态,您应该调用t.isInterrupted()

其次,您必须记住 start() 并不能保证线程立即开始执行。事实上,这种情况很少发生。新线程只有在调度程序告诉它这样做时才会真正开始执行。

所以,发生的事情是:

  • 您正在调用 start(),但线程实际上尚未启动
  • 您正在检查错误的线程,因为当前线程显然没有被中断
  • 新线程开始运行,并由于之前的 interrupt() 调用而立即中断

至于编辑的答案:

  • 您纠正了结构,但方式错误。它仍然检查当前线程,该线程没有被中断
  • 最后一行被打印,因为新线程确实被中断,所以当它启动时,它的中断标志打开 - 它立即抛出异常

关于java - 该程序中中断的执行顺序是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56498211/

相关文章:

java - 我可以使用 Inno Setup 为 Java 应用程序创建独立的 .exe 安装程序吗?

java - 在哪里用同步块(synchronized block)捕获 Object.wait() 的 InterruptedException?

java - 为什么这段代码等待 1000 毫秒而不是 500 毫秒?

java - 最小化 Java 线程上下文切换开销

JavaScript 方法执行中断

java - 使用可比较和比较器接口(interface)

java - Kindle Fire 和 GlSurfaceView.getHeight()

c++ - 隔离一个类的并发/非并发访问数据成员

c - STM32F4 PWM和中断用同一个定时器

matlab - 如何在 Matlab/GNU Octave 中停止使用 'run' 启动的脚本?