View Javadoc

1   package org.codehaus.mojo.exec;
2   
3   import java.util.Timer;
4   import java.util.TimerTask;
5   
6   /**
7    * @author <a href="mailto:dsmiley@mitre.org">David Smiley</a>
8    */
9   public class MainWithThreads extends Thread
10  {
11      public static final String ALL_EXITED = "t1(interrupted td)(cancelled timer)";
12      public static final String TIMER_IGNORED = "t1(interrupted td)";
13  
14      /** 
15       * both daemon threads will be interrupted as soon as the non daemon thread is done.
16       * the responsive daemon thread will be interrupted right away.
17       * - if the timer is cancelled (using 'cancelTimer' as argument), the timer will die on itself
18       * after all the other threads
19       * - if not, one must use a time out to stop joining on that unresponsive daemon thread
20       **/
21      public static void main( String[] args )
22      {
23          // long run so that we interrupt it before it ends itself
24          Thread responsiveDaemonThread = new MainWithThreads( 60000, "td" );
25          responsiveDaemonThread.setDaemon( true );
26          responsiveDaemonThread.start();
27  
28          new MainWithThreads( 200, "t1" ).start();
29  
30          // Timer in Java <= 6 aren't interruptible
31          final Timer t = new Timer( true );
32  
33          if ( optionsContains( args, "cancelTimer" ) )
34          {
35              t.schedule( new TimerTask()
36              {
37                  public void run()
38                  {
39                      System.out.print( "(cancelled timer)" );
40                      t.cancel();
41                  }
42              }, 400 );
43          }
44      }
45  
46      private static boolean optionsContains( String[] args, String option )
47      {
48          for (int i = 0; i < args.length; i++ )
49          {
50              if ( args[i].equals( option ) )
51                  return true;
52          }
53          return false;
54      }
55  
56      private int millisecsToSleep;
57      private String message;
58  
59      public MainWithThreads( int millisecsToSleep, String message )
60      {
61          this.millisecsToSleep = millisecsToSleep;
62          this.message = message;
63      }
64  
65      public void run()
66      {
67          try
68          {
69              Thread.sleep( millisecsToSleep );
70          }
71          catch ( InterruptedException e ) // IE's are a way to cancel a thread
72          {
73              System.out.print( "(interrupted " + message + ")" );
74              return;
75          }
76          System.out.print( message );
77      }
78  }