是否可以中断 Scanner.hasNext() [英] Is it possible to interrupt Scanner.hasNext()

查看:26
本文介绍了是否可以中断 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() 并从另一个线程尝试中断它时,除非您按 Enter,否则它将无法工作.你可能认为按下任意字符都可以,但事实并非如此,因为似乎 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();
}

这篇关于是否可以中断 Scanner.hasNext()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆