设置用户输入的超时 [英] set timeout for user's input

查看:73
本文介绍了设置用户输入的超时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以为用户输入设置计时器?等待10秒 - 进行下一步操作等等。
我的意思是例如

Is it possible to set timer for user's input? Wait 10 seconds - do next operation and etc. I mean for example

 //wait several seconds{
 String s = new BufferedReader(new InputStreamReader(System.in)).readLine();
 //wait server seconds}
 //next operation and etc.


推荐答案

不是开箱即用,没有。通常,当另一个线程关闭基础流,或者你到达输入的末尾时,Reader只会中断read()调用。

Not right out of the box, no. Normally the Reader only breaks out of a read() call when another thread closes the underlying stream, or you reach the end of the input.

因为read()不是所有可中断的这都成为一个并发编程问题。知道超时的线程需要能够中断试图读取输入的线程。

Since read() is not all that interruptible this becomes a bit of a concurrent programming problem. The thread that knows about the timeout will need to be able to interrupt the thread that's trying to read the input.

基本上,读取线程必须轮询读者的准备()方法,而不是在没有任何东西要读的情况下被锁定在read()中。如果在java.util.concurrent.Future中包装此轮询和等待操作,则使用超时调用Future的get()方法。

Essentially, the reading thread will have to poll the Reader's ready() method, rather than getting locked in read() when there's nothing to read. If you wrap this polling and waiting operation in a java.util.concurrent.Future, then you call the Future's get() method with a timeout.

本文介绍一些细节: http://www.javaspecialists.eu/archive/Issue153.html

这篇关于设置用户输入的超时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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