首页 > 解决方案 > Java:两个线程通过扫描仪打印和接收用户输入:抛出异常后程序不退出

问题描述

我有这个程序有两个线程:courseThreadquestionThread。课程线程打印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();

                }
            }
        }
    }
}

标签: javamultithreading

解决方案


这就是退出的工作原理。另一个线程打印的消息,特别是因为它在汽车上没有中断,已经在各种缓冲区中。通过使用调试器,线程被冻结或至少运行速度较慢,因此,您不会观察到它。

请参阅我的另一个答案。当我说“这不是你穿线的方式”时 - 有十亿个原因,这是十亿个原因之一。


推荐阅读