简体   繁体   English

Swing 应用程序中的 javax.swing.Timer 与 java.util.Timer

[英]javax.swing.Timer vs java.util.Timer inside of a Swing application

is this better to use javax.swing.Timer inside of a swing application instead of using java.util.Timer ?在 Swing 应用程序中使用javax.swing.Timer而不是使用java.util.Timer是否更好?

for example:例如:

Timer timer = new Timer(1000, e -> label.setText(new Date().toString()));
    timer.setCoalesce(true);
    timer.setRepeats(true);
    timer.setInitialDelay(0);
    timer.start();

or或者

new java.util.Timer().scheduleAtFixedRate(new TimerTask() {
        @Override
        public void run() {
            label.setText(new Date().toString());
        }
    }, 0, 1000);

is there any difference between this two?这两者有什么区别吗?

The difference:区别:

A java.util.Timer starts its own Thread to run the task on. java.util.Timer启动它自己的Thread来运行任务。

A javax.swing.Timer schedules tasks for execution on the EDT . javax.swing.Timer调度在EDT上执行的任务。

Now.现在。 Swing is single threaded . Swing 是单线程的

You must access and mutate Swing components from the EDT only.您必须仅从 EDT 访问和更改 Swing 组件。

Therefore, to make changes to the GUI every X seconds, use the Swing timer.因此,要每 X 秒更改一次 GUI,请使用 Swing 计时器。 To do background business logic use the other timer.要执行后台业务逻辑,请使用其他计时器。 Or better a ScheduledExecutorService .或者更好的ScheduledExecutorService

Bear one very important thing in mind;请记住一件非常重要的事情; if you spend time on the EDT it cannot spend time updating the GUI.如果你花时间在 EDT 上,它就不会花时间更新 GUI。

The main difference is that the javax.swing.Timer runs its code on the EDT while the java.util.timer runs on a separate thread.主要区别在于javax.swing.Timer在 EDT 上运行其代码,而java.util.timer在单独的线程上运行。 Because of this swing timers are best used if you are manipulating the GUI in any way.因此,如果您以任何方式操作 GUI,最好使用摆动计时器。 Although if you prefer to use a different type of timer then you can still invoke your code on the EDT.尽管如果您更喜欢使用不同类型的计时器,那么您仍然可以在 EDT 上调用您的代码。

new java.util.Timer().scheduleAtFixedRate(new TimerTask() {
    @Override
    public void run() {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
            label.setText(new Date().toString());
        }
    });
}, 0, 1000);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM