java - Java:两个线程通过扫描仪打印和接收用户输入:抛出异常后程序不退出
问题描述
我有这个程序有两个线程:courseThread和questionThread。课程线程打印Lesson continues
,而问题线程每 5 秒Finish lesson?
通过Scanner
. 我有一个引发异常的questionThreadwait()
调用。在我用来终止程序的 catch 块中,但它不能立即工作 - 只有在许多课程消息之后。同时,如果我在调试器的两个线程中都通过断点,它会很快终止程序。System.exit()
System.exit()
public class LessonNotify {
private volatile boolean finished;
private Scanner scanner = new Scanner(System.in);
private Thread lessonThread;
private Thread questionThread;
public static void main(String[] args) {
LessonNotify lesson = new LessonNotify();
lesson.lessonThread = lesson.new LessonThread();
lesson.questionThread = lesson.new QuestionThread();
lesson.lessonThread.start();
lesson.questionThread.start();
}
class LessonThread extends Thread {
@Override
public void run() {
while (!finished) {
System.out.println("Lesson continues");
}
}
}
class QuestionThread extends Thread {
private Instant sleepStart = Instant.now();
@Override
public void run() {
while (!finished) {
if (Instant.now().getEpochSecond() - sleepStart.getEpochSecond() >= 5) {
try {
lessonThread.wait();
} catch (Exception e) {
e.printStackTrace();
finished = true;
System.exit(0);
}
System.out.print("Finish a lesson? y/n");
String reply = scanner.nextLine().substring(0, 1);
switch (reply.toLowerCase()) {
case "y":
finished = true;
}
sleepStart = Instant.now();
lessonThread.notify();
}
}
}
}
}
解决方案
这就是退出的工作原理。另一个线程打印的消息,特别是因为它在汽车上没有中断,已经在各种缓冲区中。通过使用调试器,线程被冻结或至少运行速度较慢,因此,您不会观察到它。
请参阅我的另一个答案。当我说“这不是你穿线的方式”时 - 有十亿个原因,这是十亿个原因之一。
推荐阅读
- c# - C# 对 IEnumerable 的 IEnumerable 进行排序
- python - TF 2.0 W 操作已更改...当禁用急切模式并使用回调时
- javascript - 将动态数据设置为径向量规
- visual-studio-code - 更新到 catlina 和 mojave 后,流服务器和 vscode 流扩展中断
- graph-databases - 如何确保我的数据导入 Nebula Graph 成功?
- javascript - NextJS 中动态路由的命名页面
- docker - 如何在 IBM Cloud Kubernetes 服务上部署 https://github.com/docker/compose-on-kubernetes?
- r - 如何根据 R 中的另一个现有表得出百分位数
- php - 在 Symfony 4 中为 ORM 实体动态设置模式
- android - 电容器 - 为 cors 设置原点