I have a Java thread:
class MyThread extends Thread {
@Override
public void run() {
BufferedReader stdin =
new BufferedReader(new InputStreamReader(System.in));
String msg;
try {
while ((msg = stdin.readLine()) != null) {
System.out.println("Got: " + msg);
}
System.out.println("Aborted.");
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
In another thread, how do I abort the stdin.readline() call in this thread, so that this thread prints Aborted.? I have tried System.in.close(), but that doesn’t make any difference, stdin.readline() is still blocking.
I’m interested in solutions without
- busy waiting (because that burns 100% CPU);
- sleeping (because then the program doesn’t respond instantly to
System.in).
My first reaction is that a thread and
System.inreally don’t go together.So first, split this so that the thread code does not touch any static including
System.in.A thread reads from
InputStreamand passes into a buffer. Pass anInputStreaminto your existing thread that reads from the buffer but also checks that you haven’t aborted.