This discussion is archived
2 Replies Latest reply: Mar 15, 2012 6:54 AM by AjayL RSS

Interrupt a Thread

AjayL Newbie
Currently Being Moderated
I am testing a small application to interrupt the new child thread created.

My question is:

How is t.interrupt() able to interrupt the child thread? Is t the main thread that creates a new child thread?
So,shoudnt t.interrupt() interrupt the main thread rather than the child thread?
or am I missing something?
public class UsingFlagToShutdownThread extends Thread{

     private boolean running = true;
       
     // Entry point for a child thread.
     public void run() {
         while (running) {
           System.out.print(".");
           
           try {
             Thread.sleep(1000);
           } catch (InterruptedException ex) {
                Thread.currentThread().interrupt(); 
               break;

           }
         }
         
         System.out.println("Shutting down thread");
       }
       
     
       public static void main(String[] args)  throws InterruptedException {
       
            UsingFlagToShutdownThread t = new UsingFlagToShutdownThread();
            t.start();   // Create a Child Thread.
            Thread.sleep(5000);
            t.interrupt();    // How does t.interrupt() interrupt the child thread created?
       }

}

Legend

  • Correct Answers - 10 points
  • Helpful Answers - 5 points