George
George

Reputation: 81

Handling multiple threads reading input

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

Upvotes: 3

Views: 3959

Answers (1)

Raedwald
Raedwald

Reputation: 48694

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.

Upvotes: 1

Related Questions