-1

I have this program with two threads: lessonThread and questionThread. The lesson thread prints Lesson continues, while the question thread every 5 seconds asks Finish lesson? and asks a user for input via Scanner. I have a wait() call in questionThread that throws an exception. In the catch block I use System.exit() to terminate the program, however it doesn't work right away - only after many lesson messages. At the same time, if I go through breakpoints in both thread in a debugger, it System.exit() terminates the program very soon.

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();

                }
            }
        }
    }
}
parsecer
  • 4,758
  • 13
  • 71
  • 140
  • 1
    I wrote quite a bit about how to fix the 'no sleep/waiting by any thread' issue here: https://stackoverflow.com/questions/62123096/java-two-threads-executing-until-the-boolean-flag-is-false-the-second-threads/62123770#62123770 - the author has not fixed any of this. – rzwitserloot Jun 01 '20 at 01:47

1 Answers1

1

That's just how exiting works. The messages printed by the other thread, especially because it has no breaks on the car, are already in various buffers. By using a debugger the thread is frozen or at least runs slower, thus, you don't observe it.

See my other answer. When I said 'this is not how you thread' - there are a billion reasons why, and this is one of the billion.

rzwitserloot
  • 85,357
  • 5
  • 51
  • 72