The big difference is that the javax.swing.Timer
executes his task in the Event Thread (EDT = Event Dispatch Thread). Therefore it is indicated to manipulate GUI components.
The java.util.Timer
uses a Thread normal to execute their tasks. Each Timer instance creates its own Thread.
The Swing Timer documentation explains this, only not very easy to understand (in my opinion):
Although all Timers perform their Waiting using a single, Shared thread (created by the first Timer Object that executes), the action Event handlers for Timers execute on Another thread -- the Event-dispatching thread. This Means that the action handlers for Timers can Safely perform Operations on Swing Components. However, it also Means that the handlers must execute quickly to Keep the GUI Responsive.
In v 1.3, Another Timer class was Added to the Java Platform: java.util.Timer. Both it and javax.swing.Timer provide the same basic Functionality, but java.util.Timer is more general and has more Features. The javax.swing.Timer has two Features that can make it a little easier to use with Guis. First, its Event Handling Metaphor is familiar to GUI programmers and can make dealing with the Event-dispatching thread a bit Simpler. Second, its Automatic thread sharing Means that you don’t have to take special Steps to avoid spawning Too Many threads. Instead, your timer uses the same thread used to make Cursors Blink, tool tips appear, and so on.
Problems:
1) use java.util.Timer
with Swing: the methods of the Swing components must be called in the Thread EDT, which does not occur (automatically) with this Timer.
2) use javax.swing.Timer
with non-swing elements: it will be a problem if operations are delayed as they will eventually block the graphical interface.
English related: Why are there two Timer classes in Java(one under javax.swing, one under java.util )?, one of the answers even says: The version
Swing
is to render components ofSwing
. If you need time, use the useful.– Marconi
@Marconi swing.timer also controls time. Alias, it "slows" time, at least in cases where I needed to use it.
– user28595