1

《Java で考える》(第 4 版) という本を読んでいて、ソース コードの concurrency/CloseResource.java に関する質問を見つけました。メソッドが InterruptedException をスローすると、socketInput.close()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   
}
}
4

1 に答える 1

0

おそらくブロックされていSystem.in.close();ます-その行の後にprintステートメントを追加すると、おそらく到達しないことがわかります。

これはおそらく、コンソール入力を閉じることができない IDE から実行したためです。

コマンド ラインから実行すると、問題なく動作するはずです。

于 2013-05-16T09:57:04.883 に答える