- Forward


Worker and Timer Threads
An Introduction with Examples in Java


Prof. David Bernstein
James Madison University

Computer Science Department
bernstdh@jmu.edu

Print

Motivation
Back SMYC Forward
  • Remember:
    • Most GUI toolkits (including AWT and Swing) are single-threaded
  • Some Observations:
    • Some tasks can take a long time to complete so shouldn't run in the event dispatch thread
    • Some tasks need to run at "predetermined" times
  • Dealing with these Issues:
    • SwingWorker javax.swing.SwingWorker
    • Timer javax.swing.Timer (not Timer java.util.Timer )
Using a SwingWorker
Back SMYC Forward
  1. Construct a descendant of SwingWorker
  2. Call its execute() method
  3. doInBackground() is called
  4. If desired, listen for PropertyChangeEvents
  5. done() is called
Progress
Back SMYC Forward
  • In the SwingWorker:
    • Call setProgress() to generate PropertyChangeEvent objects
    • Call publish() to cause the process() method to be called
  • In the PropertyChangeListener:
    • Respond to propertyChange() messages and check the name (e.g. "progress", "state")
Cancellation
Back SMYC Forward
  • In the SwingWorker:
    • Check the value of isCancelled()
  • Outside the SwingWorker:
    • Call its cancel() method to change its state
SwingWorker Threads
Back SMYC Forward
  • The Current Thread:
    • The thread that execute() is called in.
    • (Often, but not always, the event dispatch thread.)
  • The Worker Thread:
    • The thread that doInBackground() is called in.
  • The Event Dispatch Thread:
    • The thread that process() and done() are called in (and the thread that is used to inform PropertyChangeListener objects).
An Example
Back SMYC Forward

A Calculator

javaexamples/gui/PiCalculator.java
 
An Example (cont.)
Back SMYC Forward

Using the Calculator

javaexamples/gui/PiDriver.java
 
Timed Events
Back SMYC Forward
  • Getting Started:
    • Construct a javax.swing.Timer
    • Call addActionListener() (either explicitly or using the constructor)
    • Call start() or restart()
  • Responding to Events:
    • Implement ActionListener
An Example
Back SMYC Forward

A BlinkingLabel

javaexamples/gui/BlinkingLabel.java
 
There's Always More to Learn
Back -