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
System.in
).Heinz Kabutz's newsletter shows how to abort System.in
reads using a buffer and ExecutorService
.
Now, I don't know whether this approach leaks, isn't portable or has any non-obvious side-effects. Personally, I would be reluctant to use it.
You might be able to do something with NIO channels and file descriptors - my own experiments with them didn't yield any results.