Rajat Saxena
Rajat Saxena

Reputation: 3915

Main thread does not seem to be interrupted

in my Java program main thread does not get interrupted. 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

Upvotes: 0

Views: 2081

Answers (2)

MohamedSanaulla
MohamedSanaulla

Reputation: 6242

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

Upvotes: 1

Ravi K Thapliyal
Ravi K Thapliyal

Reputation: 51711

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. 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.

As an aside, you do not need to extend Thread to call sleep() as it's a static method. Or, you can simply start infinityT directly instead of passing it as Runnable again.

Upvotes: 2

Related Questions