根据这篇文章:https ://stackoverflow.com/questions/6666659/threading-impplications-of-asynchronousbytechannel异步套接字通道的java实现不保证完成处理程序在单独的线程中被调用。所以如果你正在读入一个字节缓冲区,你如何在 wait() 之后调用 notify()?
class CH implements CompletionHandler<Integer,Integer>
{
public volatile int i = 0;
public void completed(Integer i, Integer o)
{
this.i = i;
synchronized(this)
{
this.notify();
}
}
public void failed(Throwable t, Integer o)
{
this.i = -5;
synchronized(this)
{
this.notify();
}
}
}
CH x = new CH();
synchronized (x) {
while (!(x.i == -1 || x.i == -5)) {
aschannel.read(bytebuffer, 5, TimeUnit.SECONDS, null, x);
x.wait();
if(x.i != -1 && x.i != -5){
bytebuffer.flip();
filechannel.write(bytebuffer.array,0,x.i);
bytebuffer.clear();
}
}
}