关于AsynchronousFileChannel读取数据时CompletionHandler回调函数不执行的问题

HKxutao 2017-08-14 06:18:30
public class Test144 {
public static void main(String[] args) {
Path path = Paths.get("E:/example.txt");
AsynchronousFileChannel AFC = null;
try {
AFC = AsynchronousFileChannel.open(path, StandardOpenOption.READ, StandardOpenOption.WRITE);
} catch (IOException e) {
e.printStackTrace();
}
ByteBuffer BB = ByteBuffer.allocate(64);
AFC.read(BB, 0, BB, new CompletionHandler<Integer, ByteBuffer>() {
@Override
public void completed(Integer result, ByteBuffer attachment) {
attachment.flip();
byte[] buf = new byte[attachment.limit()];
attachment.get(buf);
System.out.println(new String(buf));
}

@Override
public void failed(Throwable exc, ByteBuffer attachment) {
System.out.println("error");
}
});
}
}


这个回调函数无法执行,但是当我加入了一个延迟后就执行了,下面是加入延迟后的代码
public class Test144 {
public static void main(String[] args) throws IOException {
Path path = Paths.get("E:/example.txt");
AsynchronousFileChannel AFC = null;
try {
AFC = AsynchronousFileChannel.open(path, StandardOpenOption.READ, StandardOpenOption.WRITE);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ByteBuffer BB = ByteBuffer.allocate(64);
AFC.read(BB, 0, BB, new CompletionHandler<Integer, ByteBuffer>() {
@Override
public void completed(Integer result, ByteBuffer attachment) {
attachment.flip();
byte[] buf = new byte[attachment.limit()];
attachment.get(buf);
System.out.println(new String(buf));
}

@Override
public void failed(Throwable exc, ByteBuffer attachment) {
System.out.println("error");
}
});
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

请问有哪位仁兄为在下解惑?
...全文
218 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
hahahuhu_ 2017-08-18
  • 打赏
  • 举报
回复
额,刚才那个不清楚,都跑一行去了。。。

public interface CompletionHandler<V,A>

A handler for consuming the result of an asynchronous I/O operation. 
hahahuhu_ 2017-08-18
  • 打赏
  • 举报
回复
public interface CompletionHandler<V,A>A handler for consuming the result of an asynchronous I/O operation. 
意思是说:CompletionHandler是异步处理的,如果要显示,就要让主线程等一下它
hahahuhu_ 2017-08-18
  • 打赏
  • 举报
回复
因为你的主线程(main)在你的异步线程执行之前退出了,所以你的处理过程是不会显示的控制台上的
HKxutao 2017-08-15
  • 打赏
  • 举报
回复
有没有人啊有没有人啊有没有人啊

50,523

社区成员

发帖
与我相关
我的任务
社区描述
Java相关技术讨论
javaspring bootspring cloud 技术论坛(原bbs)
社区管理员
  • Java相关社区
  • 小虚竹
  • 谙忆
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧