简体   繁体   中英

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 ?

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.

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.

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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