. .
creates a thread and returns), the work function [which does its work, then calls invokeLater()]
and the display function [which is run by invokeLater()].
Example 11-1 Using Threads in Swing
public class NumericButtonListener implements ActionListener
public void actionPerformed(ActionEvent event) {
ThreadedJButton currentButton =
System.out.println("Pressed " + currentButton);
System.out.println(currentButton + " disabled.");
DoWorker w = new DoWorker(currentButton);
if (ThreadedSwing.useThreads)
new Thread(w).start();
class DoWorker implements Runnable {
ThreadedJButton button;
public void run() {
Thread selfName = Thread.currentThread();
System.out.println(button + " sleeping... " + selfName);
System.out.println(button + " done. " + selfName);
// This will run workComplete() in Swing main thread.
// This is the main point of the whole example.
SwingUtilities.invokeLater(new DidWorker(button));
class DidWorker implements Runnable {
ThreadedJButton button;
public void run() {
// Run only in Swing main thread.
Thread selfName = Thread.currentThread();
System.out.println(button + " reenabled. " + selfName);
Working with Unsafe Libraries
What do you do if you want to use a class library that contains unsafe methods? You could use it
in locations where it is already protected (Code Example 11-2). (HashMap is not MT-safe, but in
this code it is used only by methods that are already safely protected.) You could subclass it and
synchronize the methods (Code Example 11-3). You could use it from only a single thread.
Search WWH :
Custom Search
Previous Page
Multithreaded Programming with JAVA - Topic Index
Next Page
Multithreaded Programming with JAVA - Bookmarks