通过关闭线程底层资源关闭类似synchronized及IO阻塞的情况

 
   
public class IoBlocked implements Runnable {

    private InputStream in;

    public IoBlocked(InputStream in) {
        this.in = in;
    }

    @Override
    public void run() {
        // TODO Auto-generated method stub

        try {
            print("Wait for read()");
            int value=in.read();
//            print("in.read():"+value);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            if (Thread.currentThread().isInterrupted()) {
                print("interrupted from block IO ");
            } else {
                throw new RuntimeException(e);
            }
        }

    }
}
 
   

 

public class CloseResource {


    /**
     * 1.ExecutorService.shutdownNow(): 通过Thread.interrupt()试图停止所有正在执行的线程,并不再处理还在队列中等待的任务<br>
     * 2.ExecutorService.shutdown(): 不允许提交新任务,等待当前任务及队列中的任务全部执行完毕后退出
     * 3.当关闭阻塞的线程时会抛出异常:注意
     * @param args
     * @throws IOException
     * @throws InterruptedException
     */
    public static void main(String[] args) throws IOException, InterruptedException {
        ExecutorService executorService = Executors.newCachedThreadPool();
        ServerSocket socket = new ServerSocket(8080);// 建立一个监控8080端口的服务器...
        InputStream socketInput = new Socket("localhost", 8080).getInputStream();

        executorService.execute(new IoBlocked(socketInput));
        executorService.execute(new IoBlocked(System.in));
        TimeUnit.MILLISECONDS.sleep(100);
        print("Shutting down all Resources");
        executorService.shutdownNow();
        TimeUnit.SECONDS.sleep(1);
        print("Closeing:" + socketInput.getClass().getName());
        socketInput.close();
        TimeUnit.SECONDS.sleep(1);

        print("Closeing:" + System.in.getClass().getName());
        System.in.close();

    }

}
output:
 
  

Wait for read()

 
  

Wait for read()

 
  

Shutting down all Resources

 
  

Closeing:java.net.SocketInputStream

 
  

interrupted from block IO 

 
  

Closeing:java.io.BufferedInputStream

 

 说明两点

1.关闭Executor启动的单个线程可以通过submit获取Future对象然后调用cancel方式来中断某个特定的任务!但对于像sync,IO阻塞无效

2.有趣点:

executorService.shutdownNow()视乎发生在关闭socket的那个时刻;但没任何证据;只是通过输出而已

转载于:https://www.cnblogs.com/zhangfengshi/p/9264869.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值