我是使用Timer类的新手,因此在将其合并到我的项目之前尝试使用它.我想知道为什么这个程序在计数达到5时不会终止.即使不满足while循环的条件,程序也会继续运行.
package Timer;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Timer;
public class demo {
private static int count;
public static void main(String[] args) {
ActionListener executeThis = new ActionListener(){
@Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
System.out.println("Hello");
count++;
}
};
Timer timer = new Timer(500, executeThis);
timer.setInitialDelay(1000);
timer.start();
while(count < 5){
}
}
}
Run Code Online (Sandbox Code Playgroud)
您应该添加:
timer.stop();
Run Code Online (Sandbox Code Playgroud)
以便停止定时器调度。
另一个问题是在多线程环境中使用非原子变量。您可以使用 AtomicInteger 代替。
如果 count == 5,您可以在 actionPerformed 方法中执行此操作。
| 归档时间: |
|
| 查看次数: |
661 次 |
| 最近记录: |