如果我从
当我运行这段代码时,它会输出
System.in
开始阅读,它会阻塞线程直到获取数据。没有办法停止它。这是我尝试过的所有方法:
- 中断线程
- 停止线程
- 关闭
System.in
- 调用
System.exit(0)
确实会停止线程,但也会杀死我的应用程序,所以不理想。 - 在控制台输入字符会使方法返回,但我不能依赖用户输入。
public static void main(String[] args) throws InterruptedException {
Thread th = new Thread(() -> {
try {
System.in.read();
} catch (IOException e) {
e.printStackTrace();
}
});
th.start();
Thread.sleep(1000);
System.in.close();
Thread.sleep(1000);
th.interrupt();
Thread.sleep(1000);
th.stop();
Thread.sleep(1000);
System.out.println(th.isAlive()); // Outputs true
}
当我运行这段代码时,它会输出
true
并一直运行。
如何以可中断的方式从 System.in
读取数据?
th.close();
,对吧? - Tyler Dickson