【发布时间】: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