如果没有输入任何内容,如何检查Scanner.hasNext(System.in)超时? [英] How to check Scanner.hasNext(System.in) with a timeout if nothing is typed?

查看:148
本文介绍了如果没有输入任何内容,如何检查Scanner.hasNext(System.in)超时?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Scanner sc = new Scanner(System.in);

扫描仪可用于读取文本文件,用户输入流等。我专门用它来读取用户输入,如上所述。

Scanner can be used for reading text files, user input streams, and more. I am specifically using it for reading user input as is made clear above.

使用我上面制作的扫描仪,因为它骑'System.in,当没有下一个输入时,它的hasNext()将导致相关线程阻塞,直到它有下一个数据并且当它有数据时返回true。我想查一下,getter风格,天气有数据接下来,不是,像hasNext()返回,天气下可能有数据。

With the Scanner that I made above, because it 'rides' System.in, a call to its hasNext() when there is no next input will cause the relevant thread to block until it has data next and return true when it does. I would like to check, getter style, weather there is data next, not, like hasNext() returns, weather there could be data next.

其他问题已经解决了这个问题通过启动一个线程来等待hasNext()并解决了提问者的问题。这对我的问题没有帮助。

Other questions have resolved this by starting a thread to wait over hasNext() and that has solved the asker's problem. That wouldn't help my problem.

一个有用的代码块是调用hasNext()的代码,如果在10ms内没有得到答案,则返回false。

A useful block of code would be some that calls hasNext() and returns false if it doesn't get an answer within 10ms.

我已经阅读了规则,并试图遵守这些规则,但我认为这是我的第一个问题之一,如果我做得不对,请唱出来。

I've read the rules and tried to abide by them, but seen as this is one of my first questions, please sing out if I'm not doing this right.

提前致谢。

推荐答案

我认为没有错拥有制作人 - 消费者:

I see nothing wrong with having a Producer - Consumer here:

// Shared queue
final Queue<String> messages = new ConcurrentLinkedQueue<>();

// Non-blocking consumer
ScheduledExecutorService ses = Executors.newSingleThreadScheduledExecutor();
ses.scheduleAtFixedRate(new Runnable(){
    @Override
    public void run() {
        // non-blocking
        while((String message = messages.poll()) != null) {
            // do something
        }
    }
}, 0, 10, TimeUnit.MILLISECONDS);

// Blocking producer
Scanner sc = new Scanner(System.in);
while(sc.hasNext()) {
    messages.add(sc.next());
}

消费者可以在共享<$ c $上进行非阻塞C>队列。一旦新消息被读取,只有生产者知道它已被填充。

The consumer can then just do non-blocking on the shared Queue. Only the producer knows that it is filled as soon as a new message is read.

这篇关于如果没有输入任何内容,如何检查Scanner.hasNext(System.in)超时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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