且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2021-11-30 05:56:29

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

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

《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的两种主要调用形式:将来式和回调式