6 Replies Latest reply on Apr 19, 2013 3:40 AM by jtahlborn

    why can't I interrupt the main thread from a child thread with this code?

    910573
      I am trying to find an elegant way for a child thread (spawned from a main thread) to stop what its doing and tell the main thread something went wrong. I thought that if I invoke mainThread.interrupt() from the child thread by giving the child thread a reference to the main thread, that would do the trick. But it doesn't work all the time. I want to know why. Here's my code below:

      The main class:

      /**
      * IF YOU RUN THIS OFTEN ENOUGH, YOU'LL NOTICE THE "Child Please!" MESSAGE NOT SHOW AT SOME POINT. WHY?
      */
      public class InterruptingParentFromChildThread
      {
           public static void main( String args[] )
           {
                Thread child = new Thread( new ChildThread( Thread.currentThread() ) );
                
                child.start();
                
                try
                {
                     child.join();
                }
                catch( InterruptedException e )
                {
      // THE LINE BELOW DOESN'T GET PRINTED EVERY SINGLE TIME ALTHOUGH IT WORKS MOST TIMES, WHY?
                     System.out.println( "Child please!" );
                }
                System.out.println( "ALL DONE!" );
           }
      }

      The class for the child thread:

      public class ChildThread implements Runnable
      {
           Thread mParent;
           
           
           public ChildThread( Thread inParent )
           {
                mParent = inParent;
           }
           
           public void run()
           {
                System.out.println( "In child thread." );
                System.out.println( "Let's interrupt the parent thread now." );
                // THE COMMENTED OUT LINE BELOW, IF UNCOMMENTED, DOESN'T INVOKE InterruptedException THAT CAN BE CAUGHT IN THE MAIN CLASS' CATCH BLOCK, WHY?
                //Thread.currentThread().interrupt();
                
                // THIS LINE BELOW ONLY WORKS SOMETIMES, WHY?
                mParent.interrupt();
           }
      }