javax.swing.Timer vs java.util.Timer inside of a S

2019-01-20 12:29发布

问题:

is this better to use javax.swing.Timer inside of a swing application instead of using 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?

回答1:

The difference:

A java.util.Timer starts its own Thread to run the task on.

A javax.swing.Timer schedules tasks for execution on the EDT.

Now. Swing is single threaded.

You must access and mutate Swing components from the EDT only.

Therefore, to make changes to the GUI every X seconds, use the Swing timer. To do background business logic use the other timer. Or better a ScheduledExecutorService.

Bear one very important thing in mind; if you spend time on the EDT it cannot spend time updating the GUI.



回答2:

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. Because of this swing timers are best used if you are manipulating the GUI in any way. Although if you prefer to use a different type of timer then you can still invoke your code on the 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);