【发布时间】:2018-09-06 07:39:55
【问题描述】:
如果我从System.in 开始读取,它将阻塞线程直到它获取数据。没有办法阻止它。以下是我尝试过的所有方法:
- 中断线程
- 停止线程
- 关闭
System.in - 调用
System.exit(0)确实会停止线程,但它也会杀死我的应用程序,所以并不理想。 - 在控制台中输入 char 会使方法返回,但我不能依赖用户输入。
无效的示例代码:
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?
【问题讨论】:
-
System.in.close()
-
@JBNizet 你真的认为我没有尝试过吗?
-
应该是
th.close();否? -
@piegames 是的,我确实这么认为。你?结果如何?
-
没用,很遗憾。
标签: java multithreading inputstream system.in