关闭底层资源强行中断

对于IO这种资源无法通过interrupt()方法中断,但是在实际应用中想中断的话,可以尝试关闭任务在其上发生中断的底层资源。
=================
public class IOBlocked implements Runnable{

private InputStream is;

public IOBlocked(InputStream is) {
this.is=is;
}


@Override
public void run() {
// TODO Auto-generated method stub
System.out.println("Waiting For Read...");
try {
is.read();
} catch (IOException e) {
// TODO Auto-generated catch block
if(Thread.currentThread().isInterrupted()){
System.out.println("Interrupted from blocked I/O");
}else{
throw new RuntimeException(e);
}
}
System.out.println("Exiting IOBlocked.run()");
}
}

========================强行中断方法==================
public class CloseResource {

public static void main(String[] args) throws Exception{
ExecutorService exec=Executors.newCachedThreadPool();
ServerSocket server=new ServerSocket(8080);
InputStream socketInput=new Socket("localhost",8080).getInputStream();
exec.execute(new IOBlocked(socketInput));
exec.execute(new IOBlocked(System.in));
TimeUnit.MILLISECONDS.sleep(100);
System.out.println("shut down all threads");
exec.shutdownNow();
TimeUnit.SECONDS.sleep(1);
System.out.println("closing "+socketInput.getClass().getName());
socketInput.close();
TimeUnit.SECONDS.sleep(1);
System.out.println("closing "+System.in.getClass().getName());
System.in.close();




}
}

-----------------执行结果如下:
Waiting For Read...
Waiting For Read...
shut down all threads
closing java.net.SocketInputStream
Interrupted from blocked I/O
Exiting IOBlocked.run()
closing java.io.BufferedInputStream
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值