是否可以中断Scanner.hasNext()
我有一个读取用户输入并通过网络发送的线程。线程就像这样循环:
I've got a thread that reads user input and sends it over the network. The thread sits in a loop like this:
sin = new Scanner(System.in);
while (sin.hasNextLine()) {
if (this.isInterrupted())
break;
message = sin.nextLine();
// do processing...
}
但是当我尝试中断线程时,它不会退出hasNextLine()方法。
But when I try to interrupt the thread it doesn't exit the hasNextLine() method.
我怎样才能真正退出这个循环?
How can I actually quit this loop?
尝试更换使用以下方法的sin.hasNextLine。
背后的想法是不进入阻塞读取操作,除非该流上有可用数据。
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.
我前一段时间遇到了同样的问题,这就解决了这个问题。
基本上,当你在一个线程上执行 System.in.read()
时,你尝试中断它的另一个线程,除非你按下它,否则它将无法工作输入
。您可能认为按下任何字符都应该有效,但事实并非如此,因为似乎os(或jvm的硬件抽象层)中的读操作只返回完整的行。
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.
即使 System.in.available()
也不会返回非零值,除非您按 Enter
据我所知。
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();
}