通过关闭线程底层资源关闭类似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