当前位置:编程学习 > JAVA >>

java7 NIO2(8)The Asynchronous Channel API 异步通道API

异步channel API
主要引入三个异步类: AsynchronousFileChannel,AsynchronousSocketChannel, and AsynchronousServerSocketChannel.
AsynchronousFileChannel跟FileChannel区别:不保存全局的position和offset,可以制定访问位置,也支持并发访问文件不同。
AsynchronousServerSocketChannel AsynchronousSocketChannel:能够绑定到一个制定线程池的组中,这个线程池能够用future或者CompletionHandler来对执行结果进行处理,
AsynchronousChannelGroup:执行异步IO的java线程池的组类,
AsynchronousChannelGroup.java:
public static AsynchronousChannelGroup withFixedThreadPool(int nThreads, ThreadFactory threadFactory)
public static AsynchronousChannelGroup withCachedThreadPool(ExecutorService executor,int initialSize)
public static AsynchronousChannelGroup withThreadPool(ExecutorService executor)​​​
 
我们看使用示例
[java] 
package com.mime;  
  
import java.io.IOException;  
import java.net.InetSocketAddress;  
import java.net.StandardSocketOptions;  
import java.nio.ByteBuffer;  
import java.nio.channels.AsynchronousChannelGroup;  
import java.nio.channels.AsynchronousFileChannel;  
import java.nio.channels.AsynchronousServerSocketChannel;  
import java.nio.channels.AsynchronousSocketChannel;  
import java.nio.channels.CompletionHandler;  
import java.nio.channels.FileLock;  
import java.nio.charset.Charset;  
import java.nio.file.Path;  
import java.nio.file.Paths;  
import java.nio.file.StandardOpenOption;  
import java.util.ArrayList;  
import java.util.List;  
import java.util.Set;  
import java.util.TreeSet;  
import java.util.concurrent.Callable;  
import java.util.concurrent.ExecutionException;  
import java.util.concurrent.ExecutorService;  
import java.util.concurrent.Executors;  
import java.util.concurrent.Future;  
import java.util.concurrent.ThreadLocalRandom;  
  
public class NIO2AsynchronousFileChannel {  
    public static void main(String[] args) {  
          
        asyFile();  
        asyFileChannel2();  
        asyServerSocketChannel();  
    }  
  
    // 异步文件读写示例  
    public static void asyFile() {  
        ByteBuffer buffer = ByteBuffer.allocate(100);  
        String encoding = System.getProperty("file.encoding");  
        Path path = Paths.get("/tmp", "store.txt");  
        try (AsynchronousFileChannel asynchronousFileChannel = AsynchronousFileChannel  
                .open(path, StandardOpenOption.READ)) {  
            Future<Integer> result = asynchronousFileChannel.read(buffer, 0);  
            // 读超时控制   www.zzzyk.com
            // int count = result.get(100, TimeUnit.NANOSECONDS);  
  
            while (!result.isDone()) {  
                System.out.println("Do something else while reading ...");  
            }  
            System.out.println("Read done: " + result.isDone());  
            System.out.println("Bytes read: " + result.get());  
  
            // 使用CompletionHandler回调接口异步读取文件  
            final Thread current = Thread.currentThread();  
            asynchronousFileChannel.read(buffer, 0,  
                    "Read operation status ...",  
                    new CompletionHandler<Integer, Object>() {  
                        @Override  
                        public void completed(Integer result, Object attachment) {  
                            System.out.println(attachment);  
                            System.out.print("Read bytes: " + result);  
                            current.interrupt();  
                        }  
  
                        @Override  
                        public void failed(Throwable exc, Object attachment) {  
                            System.out.println(attachment);  
                            System.out.println("Error:" + exc);  
                            current.interrupt();  
                        }  
                    });  
  
        } catch (Exception ex) {  
            System.err.println(ex);  
        }  
        buffer.flip();  
        System.out.print(Charset.forName(encoding).decode(buffer));  
        buffer.clear();  
  
        // 异步文件写示例  
        ByteBuffer buffer1 = ByteBuffer  
                .wrap("The win keeps Nadal at the top of the heap in men's"  
                        .getBytes());  
        Path path1 = Paths.get("/tmp", "store.txt");  
        try (AsynchronousFileChannel asynchronousFileChannel = AsynchronousFileChannel  
                .open(path1, StandardOpenOption.WRITE)) {  
       
补充:软件开发 , Java ,
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,