Java NIO.2版中的异步IO的两种主要调用形式:将来式和回调式

这要注意应用场合的区别,

是有异常就及时中止,还是等主进程拿结果。

《Java程序员修炼之道》此书长功力啊!

Java NIO.2版中的异步IO的两种主要调用形式:将来式和回调式



package demo.thread;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousFileChannel;
import java.nio.channels.CompletionHandler;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

public class Run {


	public static void main(String[] args) {
		try {
			Path file = Paths.get("D:\\monad\\MyStuff.txt");
			AsynchronousFileChannel channel = AsynchronousFileChannel.open(file);
			ByteBuffer buffer = ByteBuffer.allocate(100_100);
			Future<Integer> result = channel.read(buffer, 0);
			while (!result.isDone()) {
				System.out.println("heelli ,reeftims");
			}
			Integer bytesRead = result.get();
			System.out.println("Bytes read [" + bytesRead + "]");
		} catch (IOException | ExecutionException | InterruptedException e) {
			System.out.println(e.getMessage());
		}
		
		try {
			Path file = Paths.get("D:\\monad\\MyStuff.txt");
			AsynchronousFileChannel channel = AsynchronousFileChannel.open(file);
			ByteBuffer buffer = ByteBuffer.allocate(100_100);
			channel.read(buffer, 0, buffer, new CompletionHandler<Integer, ByteBuffer> () {
				public void completed(Integer result, ByteBuffer attachment) {
					System.out.println("Bytes read [" + result + "]");
				}
				public void failed(Throwable e, ByteBuffer attachment) {
					System.out.println(e.getMessage());
				}
				
			});
		} catch (IOException e) {
			System.out.println(e.getMessage());
		}
	}
		
}

Java NIO.2版中的异步IO的两种主要调用形式:将来式和回调式
上一篇:飞天加速计划·高校学生在家实践 续费任务文章


下一篇:亿方云服务进阶路:从“客户服务”到“客户成功”