- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
基于此question我想请教以下问题。假设阻塞 I/O 并且我有一段如下代码:
byte[] data = new byte[10];
someInputStream.read(data)
此代码片段将阻塞 read
调用,直到它有一些字节要读取为止。我很熟悉 read
实际上可能会读取更少的字节,并且读取的字节数将由 read
方法返回。
我的问题是这样的。假设我有:
byte[] data = new byte[10];
if (someInputeStream.available() >= 10) {
someInputStream.read(data); // ***
}
***
行是否保证不阻塞?同样,我知道这次读取可能仍读取不到 10 个字节。
最佳答案
保证不阻塞
来自Javadoc对于 InputStream
,查看 available()
方法:
Returns an estimate of the number of bytes that can be read (or skipped over) from this input stream without blocking by the next invocation of a method for this input stream. The next invocation might be the same thread or another thread. A single read or skip of this many bytes will not block, but may read or skip fewer bytes.
(强调我的。)
所以它不会阻塞,但是(如您所说)您可能无法获得完整的 10 个字节。
请注意,这是假设单线程。如果有多个线程,那么当然另一个线程可能已从 available()
和 read()
之间的流中读取数据。
关于java - 可用并读取 : can we actually be nonblocking while using blocking Java I/O?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26427436/
我是一名优秀的程序员,十分优秀!