【问题标题】:"Thinking In Java" concurrency CloseResource.java“用 Java 思考”并发 CloseResource.java
【发布时间】:2013-05-16 01:13:58
【问题描述】:

我在看《thinking In java》(第四版)一书,发现一个关于源码并发/CloseResource.java的问题。当socketInput.close()方法抛出InterruptedException时,inputStream为socketInput的线程可以正常终止,而inputStream为System.in的线程却无法退出。程序无法退出。

你能给我一些关于这个的理由吗?

    class IOBlocked implements Runnable{
private InputStream in ; 
public IOBlocked(InputStream is){
    in=is;
}
public void run(){
    try{
        System.out.println("Waiting for read():");
        in.read();
    }catch(IOException e){
        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 IOException, InterruptedException {
    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("Shutting down all threads");   
    exec.shutdownNow();   
    TimeUnit.SECONDS.sleep(1);   
    System.out.println("Closing " + socketInput.getClass().getName());   
    socketInput.close(); // Releases blocked thread   
    TimeUnit.SECONDS.sleep(1);   
    System.out.println("Closing " + System.in.getClass().getName());   
    System.in.close(); // Releases blocked thread   
}
}

【问题讨论】:

  • 资源是否关闭?如果您在关闭它后尝试从 main() 中的 System.in 读取?如果它真的关闭了,它应该抛出一个 IOException。如果 close() 永远不会完成,您将永远不会到达那条线。
  • 如果你调试这个程序,你会发现system.in.close()已经到了。

标签: java concurrency interrupt


【解决方案1】:

它可能在 System.in.close(); 上被阻止 - 如果您在该行之后添加打印语句,您可能会看到它永远不会到达。

这可能是因为您从 IDE 运行它,它不允许您关闭控制台输入。

如果你从命令行运行它,它应该可以正常工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-08
    • 2016-06-05
    • 2018-10-16
    • 2010-11-01
    • 1970-01-01
    相关资源
    最近更新 更多