简体   繁体   English

主线程似乎没有被中断

[英]Main thread does not seem to be interrupted

in my Java program main thread does not get interrupted. 在我的Java程序主线程中不会被中断。 Why? 为什么?

/*
* This class counts till infinity
*/
class infinityT extends Thread{
  int counter = 0;
  public void run(){
    try{
      while(true){
         if(counter>500){
           // this class will throw compilation error here as Thread.sleep is not a valid method here as it does not extend Thread class
            Thread.sleep(1000);
          }
        System.out.println(counter++);
      } 
    }catch(InterruptedException e){
      System.out.println("infinity Interrupted: "+counter);
    }
  }
}

class interruption{
  public static void main(String args[]){
    Thread t = new Thread(new infinityT());

    // start the thread
    t.start();

    try{
      // main thread does not seem to interrupt
      Thread.currentThread().interrupt();
      Thread.sleep(2000);
    }catch(InterruptedException e){
      System.out.println("Main thread interrupted!");
    }

    t.interrupt();
  }
}

Output: 输出:

...
...
499
500
infinity Interrupted: 501

Your main thread does get interrupted but what it doesn't do is sleep when you call Thread.sleep() because you've already set its interrupted flag. 您的线程确实被打断了,但是当您调用Thread.sleep()时它却没有进入睡眠状态 ,因为您已经设置了它的中断标志。 Hence, all or most of the numbers would get printed after the Main thread interrupted! 因此,在主线程中断后,所有或大多数数字将被打印出来 message. 信息。

If you scroll up the console (you may have to increase its buffer or just reduce the loop count to 10 or something) you should see it getting printed as well. 如果向上滚动控制台(您可能必须增加其缓冲区或仅将循环计数减少到10左右),您也应该看到它也已打印。

As an aside, you do not need to extend Thread to call sleep() as it's a static method. 顺便说一句,您不需要扩展Thread来调用sleep()因为它是静态方法。 Or, you can simply start infinityT directly instead of passing it as Runnable again. 或者,您可以直接直接启动infinityT ,而不必再次将其作为Runnable传递。

main thread gets interrupted, you might have missed it among the other outputs. 主线程被中断,您可能在其他输出中错过了它。 check carefully and if u execute the same program multiple times, see the position in which the Main thread gets interrupted 仔细检查,如果您多次执行同一程序,请查看主线程被中断的位置

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

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