主线程似乎没有被中断

时间:2015-10-08 08:54:06

标签: java multithreading

在我的Java程序主线程中不会被中断。为什么呢?

http://localhost:8080/servlet-name

输出:

/*
* 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();
  }
}

2 个答案:

答案 0 :(得分:2)

您的线程确实中断了但是当您调用 Thread.sleep()时它不会做 sleep 因为您已经设置了中断的标志。因此,在主线程中断!消息之后,将打印所有或大部分数字。

如果你向上滚动控制台(可能需要增加缓冲区或者只是将循环次数减少到10次),你应该看到它也会被打印出来。

另外,您无需将Thread扩展为调用sleep(),因为它是静态方法。或者,您只需直接启动infinityT,而不是再次将其作为Runnable传递。

答案 1 :(得分:1)

主线程被中断,你可能在其他输出中错过了它。仔细检查,如果你多次执行相同的程序,请查看主线程被中断的位置

相关问题