Reputation: 79
This is some of my example code:
public class test implements Runnable {
@Override
public void run() {
Console console = System.console();
if (console == null) {
System.exit(0);
}
String s = console.readLine();
System.out.println(s);
run();
}
}
My goal is after a few seconds to stop console.readLine().
Upvotes: 1
Views: 757
Reputation: 62129
The following is a non-blocking standard input reader so that you never have to worry about things like that anymore:
public final class NonblockingStandardInputReaderThread
{
private NonblockingStandardInputReaderThread()
{
}
public static void start( Consumer<String> lineConsumer )
{
BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(
System.in ) );
Thread backgroundReaderThread = new Thread( new Runnable()
{
@Override
public void run()
{
while( !Thread.interrupted() )
{
try
{
String line = bufferedReader.readLine();
if( line == null )
break;
lineConsumer.invoke( line );
}
catch( IOException e )
{
System.out.println( getClass().getName() + ": " + e );
}
}
}
}, NonblockingStandardInputReaderThread.class.getName() );
backgroundReaderThread.setDaemon( true );
backgroundReaderThread.start();
}
}
So, for example with this:
NonblockingStandardInputReaderThread.start( s -> System.out.println( s ) );
you can have every line of text submitted via the standard input echoed in the standard output without any blocking.
Upvotes: 0
Reputation: 413
You could set a timer around the code you want to run for a few seconds. Like so:
new java.util.Timer().schedule(
new java.util.TimerTask() {
@Override
public void run() {
// your code here
}
},
5000
);
Upvotes: 1