3

I'm working on an application (console) which contains a while loop that I'd like to allow the user to pause and resume. After some research, it appears that an additional thread tasked with waiting for user input is the correct solution.

I've been able to implement the additional thread which continually waits for input, and also has a kill method which sets the flag variable to stop the threads while() loop. Unfortunately, since the while loop does not end unless there is input, this kill flag will only become effective once the input thread's while loop has completed at least once. Since the main thread also expects input at the end of it's own loop, the user's input is taken by the input thread, causing the main thread's Scanner to miss the input unless entered twice. Is there any way to kill the input thread's while() loop immediately without it having to complete one iteration? Would some sort of a timeout feature be required? I have posted the relevant code below:

InputReader Runnable code for new Thread:

public class ReadInput implements Runnable
{
    private static volatile boolean running = true;
    Scanner user_input = new Scanner(System.in);

    public void run()
    {
        while(running)
        {
            System.out.println("ReadingInput Input Value: " + user_input.nextLine());
        }
    }

    public void kill()
    {
        running = false;
        System.out.println("Thread Killed.");
    }
}

Main Thread code:

//Start reader thread in order to scan for input without stopping main code
ReadInput reader = new ReadInput();
Thread reader_thread = new Thread(reader);
reader_thread.start();

while(code_available_for_processing)
{
    //Main Thread while() loop processing
}

//STOP Input Reader Thread before main thread requests input
reader.kill();

//Request user input for program re-run
George
  • 81
  • 1
  • 7
  • First - do you need to kill it at all before app termination? If you do, you could try closing stdin? Never tried it, don't know what will happen. Maybe it will throw in the thread, or just return with no input - either of those would be fine and allow you to check the running flag. May be worth a try:) – Martin James Dec 12 '13 at 20:11
  • You need to read non-blocking from standard input http://stackoverflow.com/questions/2249680/concurrent-non-blocking-console-keyboard-input-in-java – abasterfield Dec 12 '13 at 20:11

1 Answers1

1

Use the interruption facilities of the Thread class. That can cause a thread that is blocked waiting for input to throw an InterruptedIOException. See elsewhere for more information.

Community
  • 1
  • 1
Raedwald
  • 46,613
  • 43
  • 151
  • 237
  • I've tried this by invoking reader_thread.interrupt() in the main thread, then adding an InterruptedException catch in the ReadInput thread. The problem is that it still appears to stay in blocked mode, waiting for input. – George Dec 13 '13 at 20:52