I have a time consuming task compute()
that I want to manually abort on the user input "abort".
To this purpose I have a Runnable InputAbort
using an infinite loop and a BufferedReader
to scan for the user input. The problem arises when the user decides not to abort the long computation. In this case, the thread running InputAbort
does not get interrupted properly preventing the JVM to finish (making the thread a daemon does work, but I think there must be a way to properly end the thread).
The problem does not occur when the user aborts the computation entering "abort". It also does not occur when I delete the line s = br.readLine();
in the Runnable and the user waits for the computation to finish.
Starting the thread and the computation:
ComputationObject co = new ComputationObject();
Runnable rInputAbort = new InputAbort(co);
Thread tInputAbort = new Thread(rInputAbort);
tInputAbort.start();
co.compute();
tInputAbort.interrupt();
Runnable:
public class InputAbort implements Runnable {
private ComputationObject co;
public RunnableInputAbort(ComputationObject co) {
this.co = co;
}
@Override
public void run() {
try {
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
String s = "";
while ( ! Thread.currentThread().isInterrupted() ) {
s = br.readLine();
if ( s.equals("abort") ) {
co.abort();
Thread.currentThread().interrupt();
}
}
br.close();
isr.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}