ITeye博客

NIO响应中断

latty · 2012-11-30 15:59 · 并发 · 编程语言 · Markdown

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

}

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。