001 package org.codehaus.mojo.exec; 002 003 import java.util.Timer; 004 import java.util.TimerTask; 005 006 /** 007 * @author <a href="mailto:dsmiley@mitre.org">David Smiley</a> 008 */ 009 public class MainWithThreads extends Thread 010 { 011 public static final String ALL_EXITED = "t1(interrupted td)(cancelled timer)"; 012 public static final String TIMER_IGNORED = "t1(interrupted td)"; 013 014 /** 015 * both daemon threads will be interrupted as soon as the non daemon thread is done. 016 * the responsive daemon thread will be interrupted right away. 017 * - if the timer is cancelled (using 'cancelTimer' as argument), the timer will die on itself 018 * after all the other threads 019 * - if not, one must use a time out to stop joining on that unresponsive daemon thread 020 **/ 021 public static void main( String[] args ) 022 { 023 // long run so that we interrupt it before it ends itself 024 Thread responsiveDaemonThread = new MainWithThreads( 60000, "td" ); 025 responsiveDaemonThread.setDaemon( true ); 026 responsiveDaemonThread.start(); 027 028 new MainWithThreads( 200, "t1" ).start(); 029 030 // Timer in Java <= 6 aren't interruptible 031 final Timer t = new Timer( true ); 032 033 if ( optionsContains( args, "cancelTimer" ) ) 034 { 035 t.schedule( new TimerTask() 036 { 037 public void run() 038 { 039 System.out.print( "(cancelled timer)" ); 040 t.cancel(); 041 } 042 }, 400 ); 043 } 044 } 045 046 private static boolean optionsContains( String[] args, String option ) 047 { 048 for (int i = 0; i < args.length; i++ ) 049 { 050 if ( args[i].equals( option ) ) 051 return true; 052 } 053 return false; 054 } 055 056 private int millisecsToSleep; 057 private String message; 058 059 public MainWithThreads( int millisecsToSleep, String message ) 060 { 061 this.millisecsToSleep = millisecsToSleep; 062 this.message = message; 063 } 064 065 public void run() 066 { 067 try 068 { 069 Thread.sleep( millisecsToSleep ); 070 } 071 catch ( InterruptedException e ) // IE's are a way to cancel a thread 072 { 073 System.out.print( "(interrupted " + message + ")" ); 074 return; 075 } 076 System.out.print( message ); 077 } 078 }