我正在阅读“Thinking in java”(Fouth Edition)这本书,并找到一个关于源代码并发/ 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
}
}
答案 0 :(得分:0)
它可能在System.in.close();
上被阻止 - 如果你在该行之后添加一个print语句,你可能会看到它永远不会到达。
这可能是因为您从IDE运行它,不允许您关闭控制台输入。
如果从命令行运行它,它应该可以正常工作。