使用 while 循环等待 Swing Timer 完成不工作

Wait for Swing Timer to finish not working using a while loop

我想在执行顺序代码之前等待 Swing 计时器完成。我在网上进行了研究,同一条线上的每个问题似乎都大相径庭,没有具体的答案。但是,我确实看到了一个使用 while 循环和确定计时器是否完成的布尔值的答案。

使用我在此处设置的代码,我希望得到以下结果:

  1. 定时器的初始化开始,创建一个新的线程来执行定时器代码
  2. while 循环被读取,但由于 timerDone 布尔值暂时卡住
  3. 计时器在完成后更改布尔值
  4. while循环终止,代码继续
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class Test {
    
    public static void main(String[] args) {
        new Test();
    }
    
    
    public boolean timerDone = false;
    
    public Test() {
        start();
        System.out.println("Finished");
    }
    
    public void start() {
        new Timer(100, new ActionListener() { 
            int i = 0;
            
            public void actionPerformed(ActionEvent event) {
                i++;
                if(i == 5) {
                    timerDone = true;
                    ((Timer)event.getSource()).stop();
                }
                
            }
        }).start();
        while(!timerDone);
    }
}

但是,即使执行了计时器代码,while 循环也永远不会终止。因此,我决定创建一个包含 while 循环的新线程:

Thread t = new Thread(() -> {
    while(!timerDone);
});
t.start();

有了这个添加,println 语句“Finished”立即打印出来,程序永远不会终止。要么 1. 我怎样才能修复当前的设置?或 2. 如何正确等待 Swing 定时器终止?

而不是使用布尔标志 (timerDone = true)` 调用一个方法来完成所需的工作:

import javax.swing.*;

public class Test {

    private int counter;

    public static void main(String[] args) {
        SwingUtilities.invokeLater(()->new Test());
    }

    public Test() {
        start();
    }

    public void start() {

        counter = 0;

        new Timer(100, event -> {
            counter++;
             System.out.println("Timer is running "+ counter);
            if(counter == 5) {
                doAfterTimerStopped();
                ((Timer)event.getSource()).stop();
            }
        }).start();
    }

    private void doAfterTimerStopped(){
        System.out.println("Timer finished");
    }
}