有以下代码:
BufferedReader localReader = new BufferedReader(new InputStreamReader(System.in));
String msg=null;
System.out.println("out of while loop!");
while((msg=localReader.readLine())!=null){
System.out.println(msg)
if(msg.equals("bye")){
break;
} }
本来以为localReader.readLine()读取不到数据时会返回null,结果执行代码后不输入数据时一直停留在while循环体内等待,故readLine()方法是一个阻塞函数。Java API文档如下描述:
public String readLine()throws IOException
Reads a line of text. A line is considered to be terminated by any one of a line feed ('\n'), a carriage return ('\r'), or a carriage return followed immediately by a linefeed.
表示该方法读取一行文本,当遇到换行符"\n",回车符"\r"或者回车符后面紧跟着换行符时,该行结束并返回。没有数据时,将会一直处于等待状态。因此在进行网络连接时,应该避免使用该方法。