有以下代码:
1 BufferedReader localReader = new BufferedReader(new InputStreamReader(System.in)); 2 String msg=null; 3 System.out.println("out of while loop!"); 4 while((msg=localReader.readLine())!=null){ 5 System.out.println(msg) 6 if(msg.equals("bye")){ 7 break; 8 } 9 10 }
本来以为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"或者回车符后面紧跟着换行符时,该行结束并返回。没有数据时,将会一直处于等待状态。因此在进行网络连接时,应该避免使用该方法。
时间: 2024-10-29 10:46:28