Mohammad Faisal
Mohammad Faisal

Reputation: 5959

Interrupt a thread waiting for user input

    public class InterruptedInput {

    public static void main(String[] args) {
        InputThread th=new InputThread();  //worker thread instantiated.
        th.start();  //worker thread start.
        try{
            Thread.sleep(5000);  //main thread sleep for 5 sec.
        }catch(InterruptedException ex){}
        th.interrupt();  //worker thread interrupted.
    }
}

class InputThread extends Thread{
    int sum;
    BufferedReader br;
    public void run(){
        br=new BufferedReader(new InputStreamReader(System.in));
        try{
            sum();
            sleep(10000);  //worker thread sleep for 10 sec.
        }catch(Exception ex){
            System.out.println("sum="+sum);
        }
    }

    public void sum(){
        try{
            while(!isInterrupted()){
                sum+=Integer.parseInt(br.readLine());
            }
        }catch(Exception ex){}
    }
}

In this program, the worker thread waiting for the input by the user (which will be an integer value) and sum up until the main thread interrut() it.
But when the main thread interrupt() the worker thread its on I/O for user input and not interrupting.

The output I want to come up with this program is:
when the program executed, user have to input the integer values and after five sec. the sum of the input values is printed either the user still inputing the values or waiting for 5sec gone off. The result will be printed right after the 5th sec.

Upvotes: 1

Views: 3727

Answers (3)

daniel gratzer
daniel gratzer

Reputation: 53911

OK so the problem with this code is the fact that the statement br.readLine() must be executed before the loop conditional is checked. So to avoid this I would have 3 threads potentially.

Thread 1:

This would be the main or parent thread. In this thread you will merely count to 5 and then interrupt thread 2.

Thread 2:

In this thread you will monitor the static variable: count,then print it and interrupt thread 3 when interrupted.

Thread 3:

Here is were you would get input and and pass the input into a function which would add it to count. When interrupted do nothing.

If you have any questions let me know.

Upvotes: 1

Kevin
Kevin

Reputation: 4128

An alternative would be to allow the count to be printed at any time. Add the following to the InputThread Class:

private AtomicInt count;

public int getCount() {
   return count;
}

And have the main method print the count:

    System.out.println("Sum:" + th.getCount());

This would avoid any need for interupting threads.

Upvotes: 0

John Vint
John Vint

Reputation: 40276

Since the IO is non-interruptable you can @Override the InputThread to close the input stream

@Override
public void interrupt(){
   try{ 
       this.br.close();
   }finally{
       super.interrupt();
   }
}

Upvotes: 1

Related Questions