欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

NIO响应中断

程序员文章站 2022-07-12 19:28:50
...
不同于IO,NIO通道会自动地相应中断,代码如下:
public class NIOBlocked implements Runnable{

private final SocketChannel sc;
public NIOBlocked(SocketChannel sc) {
this.sc=sc;
}

@Override
public void run() {
// TODO Auto-generated method stub
System.out.println("Wating to read in");
try {
sc.read(ByteBuffer.allocate(1));
}catch(ClosedByInterruptException ex){

System.out.println("ClosedByInterruptException...");
}catch(AsynchronousCloseException ae){
System.out.println("AsynchronousCloseException...");
}
catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("IOException...");
}

System.out.println("Exit NIOBlocked.run()");
}

}


==============================
public class NIOInterruption {


public static void main(String[] args) throws IOException, InterruptedException{
ExecutorService exec=Executors.newCachedThreadPool();
ServerSocket server=new ServerSocket(9111);
InetSocketAddress isa=new InetSocketAddress("localhost",9111);
SocketChannel sc1=SocketChannel.open(isa);
SocketChannel sc2=SocketChannel.open(isa);
Future<?> f=exec.submit(new NIOBlocked(sc1));
exec.execute(new NIOBlocked(sc2));
exec.shutdown();
TimeUnit.SECONDS.sleep(1);
f.cancel(true);//这里可以产生中断
TimeUnit.SECONDS.sleep(1);
sc2.close();


}
}
相关标签: 中断 线程