我在看《thinking In java》(第四版)一书,找了一个关于源码concurrency/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
}
}