IDEA终端输入Ctrl+D后sc.hasNextLine仅执行一次但程序仍运行?
问题原因解析
先明确前提
在IDEA终端(类Unix终端环境)中,Ctrl+D是输入流的结束标记(EOF),作用是告知程序:当前标准输入(System.in)已经没有更多数据可以读取了。
1. 为什么sc.hasNextLine()仅执行一次就退出内层循环?
当你按下Ctrl+D时,当前的Scanner关联的System.in被标记为EOF状态。此时sc.hasNextLine()会直接返回false,内层while循环的条件不满足,自然就终止了——它只会把你按下Ctrl+D前输入的内容(如果有的话)读取一次,就退出循环。
2. 为什么程序还会持续运行?
因为外层有一个while(true)的死循环,内层循环结束后,代码会执行System.out.println(builder.toString());,然后立刻回到外层循环的开头:重新创建新的Scanner实例,再次尝试读取System.in。
但关键在于:一旦标准输入流被标记为EOF,后续所有基于System.in创建的Scanner调用hasNextLine()都会直接返回false。所以后续每次进入外层循环,内层的while循环都会直接跳过,直接执行打印语句,然后再次进入外层循环,导致程序一直重复这个流程,看起来就是“持续运行”。
原测试代码
package IOReview; import java.util.Scanner; import static java.lang.Thread.sleep; public class ThreadTest { public static void main(String[] args) { new Thread(() -> { while (true){ Scanner sc = new Scanner(System.in); StringBuilder builder = new StringBuilder(); System.out.println("Please Input the text you want:"); try { sleep(1000); } catch (InterruptedException e) { throw new RuntimeException(e); } //The while loop below will only execute once,the rest of the program will keep running; while (sc.hasNextLine()) { builder.append(sc.nextLine()); } System.out.println(builder.toString()); } }).start(); } }
内容的提问来源于stack exchange,提问作者sss lll
相关产品推荐
相关产品推荐

