Try replacing the the sin.hasNextLine
with the method below.
The idea behind is not to enter a blocking read operation unless there is data available on that stream.
I got the same problem a while ago and this fixes it.
Basically, when you perform System.in.read()
on a thread and from another thread you try to interrupt it, it won't work unless you press Enter
. You might think that pressing any character should work, but that is not true, because it seems that the read operation inside os (or the jvm's hardware abstraction layer) only returns full lines.
Even System.in.available()
won't return a non-zero value unless you press Enter
as far as i know.
private boolean hasNextLine() throws IOException {
while (System.in.available() == 0) {
// [variant 1
try {
Thread.currentThread().sleep(10);
} catch (InterruptedException e) {
System.out.println("Thread is interrupted.. breaking from loop");
return false;
}// ]
// [variant 2 - without sleep you get a busy wait which may load your cpu
//if (this.isInterrupted()) {
// System.out.println("Thread is interrupted.. breaking from loop");
// return false;
//}// ]
}
return sin.hasNextLine();
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…