这个类型的流在read时,会占用流的锁,导致close阻塞。例子如下
public class Test {
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
Process process = Runtime.getRuntime().exec("notepad");
final InputStream input = process.getInputStream();
Thread thread = new Thread(new Runnable(){
@Override
public void run() {
try {
System.out.println("read");
input.read();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
thread.start();
System.in.read();
System.out.println("close");
input.close();
System.out.println("over");
}
}
Socket类型的流就可以在read的时候close,这样read就可以返回了。
public class Main {
/**
* @param args
* @throws IOException
* @throws UnknownHostException
*/
public static void main(String[] args) throws UnknownHostException, IOException {
Socket s = new Socket("127.0.0.1", 20012);
final InputStream input = s.getInputStream();
Thread th = new Thread(new Runnable(){
@Override
public void run() {
try {
input.read();
System.out.println("read return");
} catch (IOException e) {
e.printStackTrace();
}
}
});
th.start();
System.in.read();
input.close();
System.out.println("over");
}
}