java多线程之NIO的中断

package com.eshroe.sweetop.concurrency; import java.io.IOException; import java.net.InetSocketAddress; import java.net.ServerSocket; import java.nio.ByteBuffer; import java.nio.channels.AsynchronousCloseException; import java.nio.channels.ClosedByInterruptException; import java.nio.channels.SocketChannel; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; class NIOBlocked implements Runnable { private final SocketChannel sc; public NIOBlocked(SocketChannel sc) { this.sc = sc; } public void run() { System.out.println("waiting for read() in: "+this); try { sc.read(ByteBuffer.allocate(1)); }catch(ClosedByInterruptException e){ System.out.println("ClosedByInterruptException"); }catch(AsynchronousCloseException e){ System.out.println("AsynchronousCloseException"); }catch (IOException e) { e.printStackTrace(); } System.out.println("Exiting NIOBlocked run() "+this); } } public class NIOInterruption { public static void main(String[] args) throws Exception { ExecutorService exec=Executors.newCachedThreadPool(); ServerSocket server=new ServerSocket(8080); InetSocketAddress isa=new InetSocketAddress("localhost",8080); 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(); } }

输出结果:

waiting for read() in: com.eshroe.sweetop.concurrency.NIOBlocked@cd2c3c

waiting for read() in: com.eshroe.sweetop.concurrency.NIOBlocked@a97b0b

ClosedByInterruptException

Exiting NIOBlocked run() com.eshroe.sweetop.concurrency.NIOBlocked@cd2c3c

AsynchronousCloseException

Exiting NIOBlocked run() com.eshroe.sweetop.concurrency.NIOBlocked@a97b0b

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值