java - NIO非阻塞表现在什么地方?
高洛峰
高洛峰 2017-04-18 09:42:57
0
2
495

都是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); 的时候岂不是也是阻塞的?

高洛峰
高洛峰

拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...

reply all(2)
刘奇

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

Peter_Zhu

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. ,

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!