使用while循环等待Swing Timer结束不工作



我想在执行顺序代码之前等待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。我怎样才能正确地等待一个摇摆定时器终止?

不使用布尔标志(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");
}
}

最新更新