package Thread.interrupt; import java.io.IOException; import java.net.InetSocketAddress; import java.net.ServerSocket; import java.nio.ByteBuffer; import java.nio.channels.SocketChannel; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; /* * æ®éçIoé»å¡ï¼ä¸å¯ä¸æï¼å°±æ¯è¿åçå¨é»å¡ç¶æï¼ä¸è½è·³åºé»å¡ç¶æï¼ * è¿æéï¼ï¼ä¹æ¯ä¸å¯ä¸æç * * sleepé»å¡æ¯å¯ä¸æçï¼å¯ä»¥è·³åºé»å¡ç¶æ * * * nioèªå¨ååºä¸æ * * */ class NIOBlocked implements Runnable{ private final SocketChannel channel; public NIOBlocked(SocketChannel socketChannel){ this.channel=socketChannel; } public void run() { try { System.out.println("waiting for read() in:"+this); channel.read(ByteBuffer.allocate(1)); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("exiting NIOBlocked.run()"); } } public class NIOInterruption { public static void main(String[] args) { ExecutorService es=Executors.newCachedThreadPool(); try { ServerSocket serverSocket=new ServerSocket(8080); InetSocketAddress isa=new InetSocketAddress("localhost", 8080); SocketChannel channel1=SocketChannel.open(isa); SocketChannel channel2=SocketChannel.open(isa); //å°ä¸æåéç»ä¸ä¸ªç¹å®ççº¿ç¨ Future> future=es.submit(new NIOBlocked(channel1)); es.execute(new NIOBlocked(channel2)); //ä¸æä»»å¡ es.shutdown(); future.cancel(true); //å ³éåºå±èµæºæ¥éæ¾é channel2.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }