NIO响应中断

不同于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();


}
}

你可能感兴趣的:(线程,中断)