zoukankan      html  css  js  c++  java
  • NIO(一)缓冲区

    I/O的基本概念

    1. 同步和异步的概念:
      所谓的同步就是在发出一个请求的时候,如果没有得到结果,就不返回。即调用者主动等待返回结果。
      所谓的异步:调用之后直接返回结果,一般通过回调函数来处理这个应用。
    2. 阻塞和非阻塞的概念:
      阻塞:在调用没有得到结果之前,当前线程会被挂起。调用线程得到结果之后才会返回。
      非阻塞:不能得到结果之前,改调用不会阻塞住当前的线程。

    缓冲区

    缓冲区其实就是一块数组,然后对这一块数组进行一系列的操作,它包括以下几个常用的方法:

    1分配空间给缓冲区
    2.往缓冲区中添加数据调用put方法
    3.调用flip方法切换为读状态
    4.读取完毕调用clear方法重新设置位置为0。

    常用方法解析

    1.clear方法不清除数据,只是改变当前limit值

      public final Buffer clear() {
            position = 0;
            limit = capacity;
            mark = -1;
            return this;
        }
    

    2.flip方法允许输出

     public final Buffer flip() {
            limit = position;
            position = 0;
            mark = -1;
            return this;
        }
    

    3.rewind方法使posotion方法置为0

     public final Buffer rewind() {
            position = 0;
            mark = -1;
            return this;
        }
    

    4.判断两个缓冲区是否相等的方法,代码如下:

        public boolean equals(Object ob) {
            if (this == ob)
                return true;
            if (!(ob instanceof CharBuffer))
                return false;
            CharBuffer that = (CharBuffer)ob;
            if (this.remaining() != that.remaining())
                return false;
            int p = this.position();
            for (int i = this.limit() - 1, j = that.limit() - 1; i >= p; i--, j--)
                if (!equals(this.get(i), that.get(j)))
                    return false;
            return true;
        }
    

    要满足几下条件才能算相等。
    1、对象要相同
    2、剩余的空间要相同
    3、从position到limit区间的数据要相等才能确认数据是否相等。

  • 相关阅读:
    html5+css3中的background: -moz-linear-gradient 用法 (转载)
    CentOS 安装Apache服务
    Linux 笔记
    CURL 笔记
    Spring Application Context文件没有提示功能解决方法
    LeetCode 389. Find the Difference
    LeetCode 104. Maximum Depth of Binary Tree
    LeetCode 520. Detect Capital
    LeetCode 448. Find All Numbers Disappeared in an Array
    LeetCode 136. Single Number
  • 原文地址:https://www.cnblogs.com/master-image/p/7943737.html
Copyright © 2011-2022 走看看