// GetUserInput.java // Object: write a program that asks for user input, and // waits a prescribed number of seconds. If the user doesn't // respond in time, the program continues anyway. // By Kip Irvine // Updated 9/7/03 import java.lang.Thread; import java.io.*; class StringInputThread extends Thread { // this daemon thread starts itself as soon as it is constructed public StringInputThread( String msg ) { message = msg; inputString = ""; setDaemon( true ); start( ); } public void run( ) { System.out.print("You have 5 seconds to enter your name: "); try { inputString = input.readLine( ); } catch( IOException e ) { } } public String getInputValue( ) { return inputString; } BufferedReader input = new BufferedReader(new InputStreamReader(System.in)); private String inputString; private String message; } class ThreadDemo { public static void main( String[] args ) { StringInputThread getName = new StringInputThread ( "Enter your name" ); try { getName.join( 5000 ); // wait for getName to finish getName.interrupt( ); // time's up--interrrupt it } catch( InterruptedException e ) { } String theName = getName.getInputValue( ); if( theName.length( ) == 0 ) System.out.println( "\nToo late!" ); else System.out.println( "Hello, " + theName ); } }