---
title: "NIO响应中断"
author: "latty"
date: "2012-11-30T15:59:55Z"
tags: []
categories: ["编程语言"]
slug: "nio"
draft: false
lastmod: "2011-10-11T11:04:48Z"
id: 1189403
url: "https://latty.iteye.com/blog/1189403"
---

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