zoukankan      html  css  js  c++  java
  • 【Java__IO与NIO】同步阻塞和同步非阻塞

    0 概述

    • 同步 :两个同步任务相互依赖,并且一个任务必须以依赖于另一任务的某种方式执行。 比如在A->B事件模型中,你需要先完成 A 才能执行B。 再换句话说,同步调用种被调用者未处理完请求之前,调用不返回,调用者会一直等待结果的返回。
    • 异步: 两个异步的任务完全独立的,一方的执行不需要等待另外一方的执行。再换句话说,异步调用种一调用就返回结果不需要等待结果返回,当结果返回的时候通过回调函数或者其他方式拿着结果再做相关事情,

    • 阻塞: 阻塞就是发起一个请求,调用者一直等待请求结果返回,也就是当前线程会被挂起,无法从事其他任务,只有当条件就绪才能继续。
    • 非阻塞: 非阻塞就是发起一个请求,调用者不用一直等着结果返回,可以先去干其他事情。

    1 BIO (Blocking I/O) 同步阻塞

    	public static String readFile(String path) {
    		StringBuffer sb = new StringBuffer();
    		BufferedReader reader = null;
    		try {
    			reader = new BufferedReader(new FileReader(path));
    			String len;
    			while ((len = reader.readLine()) != null) {
    				sb.append(len);
    			}
    		} catch (Exception e) {
    			e.printStackTrace();
    		} finally {
    			if (reader != null) {
    				try {
    					reader.close();
    				} catch (IOException e) {
    					e.printStackTrace();
    				}
    			}
    		}
    		return sb.toString();
    	}
    

    2 NIO (New I/O) 同步非阻塞

    	public static void copyFileUseNIO(String src, String dst) throws Exception {
    		// 声明源文件和目标文件
    		FileInputStream fi = new FileInputStream(new File(src));
    		FileOutputStream fo = new FileOutputStream(new File(dst));
    		// 获得传输通道channel
    		FileChannel inChannel = fi.getChannel();
    		FileChannel outChannel = fo.getChannel();
    		// 获得容器buffer
    		ByteBuffer buffer = ByteBuffer.allocate(1024);
    		while (true) {
    			// 判断是否读完文件
    			int eof = inChannel.read(buffer);
    			if (eof == -1) {
    				break;
    			}
    			// 重设一下buffer的position=0,limit=position
    			buffer.flip();
    			// 开始写
    			outChannel.write(buffer);
    			// 写完要重置buffer,重设position=0,limit=capacity
    			buffer.clear();
    		}
    		inChannel.close();
    		outChannel.close();
    		fi.close();
    		fo.close();
    	}
    

    参考

    BIO,NIO,AIO 总结
    java IO、NIO、AIO详解

  • 相关阅读:
    How to install VXDIAG Honda, Toyota and JLR SDD software
    16% off MPPS V16 ECU tuning tool for EDC15 EDC16 EDC17
    Cummins INSITE locked and ask for verification code
    How to use BMW Multi Tool 7.3 to replace lost key for BMW X1
    Bleed Brake Master Cylinder with Intelligent Tester IT2
    Porsche Piwis Tester II “No VCI has been detected”,how to do?
    Creader VIII VS. Creader VII+
    How to solve GM MDI cannot complete the installation
    汽车OBD2诊断程序开发 (原文转载,思路很清晰!)
    汽车节温器单片机开发思路
  • 原文地址:https://www.cnblogs.com/kikyoqiang/p/13305679.html
Copyright © 2011-2022 走看看