zoukankan      html  css  js  c++  java
  • JAVA NIO 不是同步非阻塞I/O吗,为什么说JAVA NIO提供了基于Selector的异步网络I/O?

    https://www.zhihu.com/question/27991975

    java nio的io模型是同步非阻塞,这里的同步异步指的是真正io操作(数据内核态用户态的拷贝)是否需要进程参与。

    而说java nio提供了异步处理,这个异步应该是指编程模型上的异步。基于reactor模式的事件驱动,事件处理器的注册和处理器的执行是异步的。

    JAVA NIO是同步非阻塞io。同步和异步说的是消息的通知机制,阻塞非阻塞说的是线程的状态 。
    下面说说我的理解,client和服务器建立了socket连接:
    1、同步阻塞io(Blocking, synchronous):client在调用read()方法时,stream里没有数据可读,线程停止向下执行,直至stream有数据。
    阻塞:体现在这个线程不能干别的了,只能在这里等着
    同步:是体现在消息通知机制上的,即stream有没有数据是需要我自己来判断的。
    device = IO.open()
    data = device.read() # thread will be blocked until there is no data in the device
    print(data)
    2、同步非阻塞io(Non-blocking, synchronous):调用read方法后,如果stream没有数据,方法就返回,然后这个线程就就干别的去了。
    非阻塞:体现在,这个线程可以去干别的,不需要一直在这等着
    同步:体现在消息通知机制,这个线程仍然要定时的读取stream,判断数据有没有准备好,client采用循环的方式去读取,可以看出CPU大部分被浪费了
    device = IO.open()
    while True:
        is_ready = IO.poll(device, IO.INPUT, 5) # returns control if 5 seconds have elapsed or there is data to read (INPUT)
        if is_ready:
            data = device.read()
            break # exit loop
        else:
            print("There is no data to read!")
    3、异步非阻塞io(Non-blocking, asynchronous):服务端调用read()方法,若stream中无数据则返回,程序继续向下执行。当stream中有数据时,操作系统会负责把数据拷贝到用户空间,然后通知这个线程,这里的消息通知机制就是异步!而不是像NIO那样,自己起一个线程去监控stream里面有没有数据!
    ios = IO.IOService()
    device = IO.open(ios)
    
    def inputHandler(data, err):
        "Input data handler"
        if not err:
            print(data)
    
    device.readSome(inputHandler)
    ios.loop() # wait till all operations have been completed and call all appropriate handlers
  • 相关阅读:
    poj 2029 Get Many Persimmon Trees 夜
    poj 1191 棋盘分割 夜
    DOM (四)
    div拖拽, onmousedown ,onmousemove, onmouseup
    闭包理解
    DOM(一)
    内存溢出与内存泄漏
    div随鼠标移动而移动(滚动条)
    对象继承模式
    DOM(二)
  • 原文地址:https://www.cnblogs.com/shikamaru/p/8342524.html
Copyright © 2011-2022 走看看