我有几个InputStream
需要以非阻塞的方式读取。以下是示例:
public Result getResult(InputStream ... inputStreams) {
final Result result = new Result();
for (InputStream stream : inputStreams) {
// TODO: read input streams without blocking here
// write output using result.log.add(...) when it gets to a \n (newline)
}
return result;
}
public class Result {
public final Collection<String> log = new ConcurrentLinkedDeque<>();
}
我可以通过以下方式为每个InputStream
开启一个新线程:
new Thread(() -> { // TODO: 在此读取 }).start()
。
甚至可以使用ExecutorService,但我宁愿不自己启动线程,而是让JDK来管理。这种做法是否可能?
(我有一个进程,根据请求打印Result.log
。)
InputStream
中读取所有可用数据),我发现这个问题很有用:https://stackoverflow.com/questions/804951/is-it-possible-to-read-from-a-inputstream-with-a-timeout - undefined