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
).
readLine
inMyThread
raise aSocketException
with"Socket closed"
. So I can abortMyThread
this way. – Ganley