“等待”对于 Java 中的流
可能的重复:
是否可以从Java读取输入流超时?
我正在从源可能挂起的流中读取数据。我如何“等待” BufferedReader.readLine() 返回一个字符串最长一段时间(比如五秒)并在没有任何结果的情况下继续程序读?
Possible Duplicate:
Is it possible to read from a Java InputStream with a timeout?
I'm reading from a stream whose origin may hang. How can I "wait" for a BufferedReader.readLine()
to return a string for a maximum of a certain time (say five seconds) and continue the program if nothing is read?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
BufferedReader 有ready() 方法,它检查输入流是否有准备读取的内容。您可以将其与计时器类或其他东西结合使用。
BufferedReader has ready() method which checks whether the input stream has something ready to read or not. You can use that combined with a timer class or something.
需要注意的是,这是一个 IO 阻塞调用。因此,中断当前正在执行该语句的线程绝对不会产生任何影响。
执行此操作的一种简洁方法是通过将 ExecutorService 包装在 Callable 实现中来执行此调用。通过对返回的 future 调用 get(timeout) 方法,您既可以手动控制超时,也可以优雅地处理中断。
如果该线程被中断,您将需要关闭底层资源,以便调用本身真正返回并且不会泄漏线程。像 myInputStream.close() 之类的东西。
It is important to note that this is an IO blocking call. As such, interrupting the thread currently executing this statement will have absolutely no effect.
A clean way of doing this would be to execute this call with an ExecutorService by wrapping it in a Callable implementation. By calling the get(timeout) method on the returned future, you can both control the timeout manually as well as handle interruptions gracefully.
If this thread is interrupted, you will want to close the underlying resource so that the call itself will actually return and you don't leak threads. Something like myInputStream.close().