Java:执行两个线程,直到boolean标志为false:第二个线程的第一次运行都会停止第一个线程

问题描述 投票:0回答:2

我有这个具有三个线程的线程程序:mainlessonThreadquestionThread

它是这样的:

  • [Lesson continues继续打印,而finished变量为true
  • [[questionThread每隔5秒询问一次Finish lesson?,如果答案为y,则会将finished设置为false
问题是Lesson continues

从不

在第一次被问到问题后就被打印出来:enter image description here

此外,如图所示,有时[[lessonThread

会潜入Lesson continues,然后用户才能输入

questionThread问题的答案。

public class Lesson { private boolean finished; private boolean waitingForAnswer; private Scanner scanner = new Scanner(System.in); private Thread lessonThread; private Thread questionThread; public static void main(String[] args) { Lesson lesson = new Lesson(); 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 && !waitingForAnswer) { System.out.println("Lesson continues"); } } } class QuestionThread extends Thread { private Instant sleepStart = Instant.now(); private boolean isAsleep = true; @Override public void run() { while (!finished) { if (isAsleep && Instant.now().getEpochSecond() - sleepStart.getEpochSecond() >= 5) { System.out.print("Finish a lesson? y/n"); waitingForAnswer = true; String reply = scanner.nextLine().substring(0, 1); switch (reply.toLowerCase()) { case "y": finished = true; } waitingForAnswer = false; isAsleep = true; sleepStart = Instant.now(); } } } } } 我认为这里waitingForAnswer = true可能有问题,但是
lessonThread
有5秒钟,直到

questionThread

再次提出问题,在此期间waitingForAnswerfalse。] >非常感谢您的帮助。

EDIT

:我在lessonThread的循环中找到了一笔购买,并将其更改为:

@Override public void run() { while (!finished) { if (!waitingForAnswer) { System.out.println("Lesson continues"); } } }

但是我得到相同的结果。

EDIT

:我可以在调试器中运行它:

enter image description here

我有一个具有三个线程的线程程序:main,lessonThread,questionThread。它是这样工作的:当finished变量为true时,课程继续继续打印;每5 ...
java multithreading concurrency thread-safety
2个回答
0
投票

0
投票
© www.soinside.com 2019 - 2024. All rights reserved.