zoukankan      html  css  js  c++  java
  • 通过关闭线程底层资源关闭类似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的那个时刻;但没任何证据;只是通过输出而已
  • 相关阅读:
    Java 中字符串的格式化
    JAVA字符串格式化-String.format()的使用
    JVM参数配置大全
    Java日期时间使用总结
    Java 通过JDBC连接Mysql数据库的方法和实例
    在eclipse导入Java 的jar包的方法 JDBC
    CentOS 7中如何安装mysql server
    python处理excel
    Chrome Developer Tools:Network Panel说明
    Mysql命令alter add:增加表的字段
  • 原文地址:https://www.cnblogs.com/zhangfengshi/p/9264869.html
Copyright © 2011-2022 走看看