有以下代码:      

 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"或者回车符后面紧跟着换行符时,该行结束并返回。没有数据时,将会一直处于等待状态。因此在进行网络连接时,应该避免使用该方法。

相关文章:

  • 2021-10-22
  • 2022-02-05
  • 2021-04-19
  • 2021-07-28
  • 2021-08-23
  • 2021-12-28
  • 2022-01-20
  • 2021-08-01
猜你喜欢
  • 2021-09-09
  • 2022-01-11
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案