都是NIO是面向缓冲区的非阻塞的io,面向缓冲区倒是好理解,非阻塞到底体现在什么地方?莫不是selector使得NIO是非阻塞的?像下面代码:
RandomAccessFile aFile = new RandomAccessFile("data/nio-data.txt", "rw");
FileChannel inChannel = aFile.getChannel();
ByteBuffer buf = ByteBuffer.allocate(48);
int bytesRead = inChannel.read(buf);
while (bytesRead != -1) {
System.out.println("Read " + bytesRead);
buf.flip();
while(buf.hasRemaining()){
System.out.print((char) buf.get());
}
buf.clear();
bytesRead = inChannel.read(buf);
}
aFile.close();
在int bytesRead = inChannel.read(buf);
的时候岂不是也是阻塞的?
怪我咯2017-04-18 09:44:57
The read event is registered on the selector of the server. At a certain moment, the client sends some data to the server. If I/O is blocked, the read() method will be called to read the data blockingly, and the NIO server will add it to the selector. A read event. The processing thread of the server will access the selector in a polling manner. If it finds that interesting events arrive when accessing the selector, these events will be processed. If no interesting events arrive, the processing thread will block until the interesting events arrive.
You can see here for details:
Java blocking IO and non-blocking IO
天蓬老师2017-04-18 09:44:57
First of all, you need to know the concepts of blocking and non-blocking. Blocking means that this thread cannot do anything else and can only wait here. Non-blocking means that this thread can do other things and does not need to wait here all the time.
Before talking about the non-blocking principle of NIO, we need to talk about traditional io first. Traditional IO is transmitted by bytes, that is, one byte is transmitted at a time. In order to improve the efficiency of data transmission, the input and output mode with buffer is introduced, so that a large number of bytes can be transmitted each time. However, this will cause the program to wait until the read (write) buffer is not full. The stream cannot be read (written) until it is full or closed. This causes the program to block and reduces the execution efficiency of the program. ,