且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

设置用户输入的超时

更新时间:2023-12-04 17:45:04

不是开箱即用,没有。通常,当另一个线程关闭基础流,或者你到达输入的末尾时,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