如何在Java中正确处理定时器?

我希望我的计时器在5秒时间内只执行一次actionPerformed方法,但它在控制台“Hello”中写了很多次:

import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.Timer; public class X{ public static void main(String args[]) { ActionListener actionListener = new ActionListener() { public void actionPerformed(ActionEvent actionEvent) { System.out.println( "Hello" ); } }; Timer timer = new Timer( 5000, actionListener ); timer.start(); } } 

我怎样才能达到我想要的效果? 谢谢

如前所述,最好使用java.util.Timer ,但在开始之前也可以使用setRepeats() :

 timer.setRepeats(false); 

不要忽视使用事件派发线程 。 java.util.Timer没有任何问题 ,但javax.swing.Timer与Swing有几个优点。

 import java.awt.EventQueue; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.Timer; public class X { public static void main(String args[]) { EventQueue.invokeLater(new Runnable() { @Override public void run() { ActionListener actionListener = new ActionListener() { public void actionPerformed(ActionEvent actionEvent) { System.out.println("Hello"); } }; Timer timer = new Timer(5000, actionListener); timer.start(); } }); } } 

如果使用java.util.Timer ,请使用continuation更新GUI。

听起来你想要一个java.util.Timer而不是javax.swing.Timer

 class MyTask extends TimerTask { public void run() { System.out.println("Hello"); } } 

接着

 timer = new Timer(); timer.schedule(new MyTask(), 5000); 

这应该做的伎俩!

 new JFrame().setVisible(true);