2014-10-03 45 views
1
Scanner sc = new Scanner(System.in); 

扫描仪可用于读取文本文件,用户输入流等。我正在使用它来阅读用户输入,如上所述。如何检查Scanner.hasNext(System.in)在没有输入任何内容的情况下超时?

使用上面我做的Scanner,因为它'乘坐'System.in,当没有下一个输入时调用它的hasNext()会导致相关线程阻塞,直到它有下一个数据并返回true时它确实如此。我想检查一下,getter风格,接下来的天气有数据,而不是像hasNext()返回的那样,接下来的天气可能会有数据。

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

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

我已阅读规则并试图遵守这些规则,但由于这是我的第一个问题之一,如果我没有这样做,请唱出来。

在此先感谢。

回答

1

我认为没有错与具有生产者 - 消费者在这里:

// 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()); 
} 

消费者可以再只是在共享Queue无阻塞。只有生产者知道一旦读取新消息它就被填充。

相关问题