Presentation is loading. Please wait.

Presentation is loading. Please wait.

2006-08-16 Java Threads 1 1 Threading and Concurrent Programming in Java Threads and Swing D.W. Denbo.

Similar presentations


Presentation on theme: "2006-08-16 Java Threads 1 1 Threading and Concurrent Programming in Java Threads and Swing D.W. Denbo."— Presentation transcript:

1 2006-08-16 Java Threads 1 1 Threading and Concurrent Programming in Java Threads and Swing D.W. Denbo

2 2006-08-16Java Threads2 Threads and Swing The most important thing to remember about using Swing in a concurrent application is: Swing is not thread-safe!! If you try to manipulate user interface elements from multiple threads, then your user interface can become corrupted.

3 2006-08-16Java Threads3 Outline “Single Thread” Rule Exceptions to the rule Event dispatching A Swing Worker

4 2006-08-16Java Threads4 SwingThreadTest

5 2006-08-16Java Threads5 The “Single Thread” Rule Once a Swing component has been realized, all code that might affect or depend on the state of that component should be executed in the event- dispatching thread. Realized means that the component’s paint method has been or might be called.

6 2006-08-16Java Threads6 Swing Threads In a Swing program, the main method typically does the following: –First it calls a constructor that lays out the components in a frame window. –Then it invokes the setVisible method on the frame window. When the first window is shown, a second thread is created, the event dispatch thread. All event notifications, such as calls to actionPerformed or paintComponent, run in the event dispatch thread.

7 2006-08-16Java Threads7 General Rules 1.If an action takes a long time, fire up a new thread to do the work. Otherwise the application will seem “dead”. 2.If an action can block on input or output, use a new thread. 3.If you need to wait for a specific amount of time, use timer events. 4.Work you do in your threads can’t touch the user interface. Read any UI info before launching your thread and update UI info from the event dispatch thread after finishing.

8 2006-08-16Java Threads8 Exceptions to the Rule A few methods are thread-safe: In the Swing documentation, those methods are marked with “This method is thread safe, although most Swing methods are not.” For example: –JTextArea insert append replaceRange –JEditorPane replaceSelection setText

9 2006-08-16Java Threads9 An applications GUI can often be constructed and shown in the main thread. public class MyApplication { public static void main(String[] args) { Jframe f = new Jframe(“Labels”); // Add components to the frame here... f.pack(); f.setVisible(true); // Don’t do any more GUI work here... }

10 2006-08-16Java Threads10 An applet’s GUI can be constructed and shown in the init method. Existing browsers don’t draw the applet until after its init and start methods have been called. The following JComponent methods are safe to call from any thread: –repaint –revalidate –invalidate

11 2006-08-16Java Threads11 Listener list can be modified from any thread: It’s always safe to call the addListenerTypeListener and removeListenerTypeLister methods. The add/remove operations have no effect on an event dispatch that’s under way.

12 2006-08-16Java Threads12 Event Dispatching Most post-initialization GUI work naturally occurs in the event-dispatching thread. Once the GUI is visible, most programs are driven by events such as button actions or mouse clicks, which are always handled in the event dispatch thread.

13 2006-08-16Java Threads13 Some programs need to perform non-event- driven GUI work. –Programs that must perform a lengthy initialization operation before they can be used. You may want to display a “splash” screen. The initialization should not occur in the event dispatch thread, however, after initialization the GUI update/change should occur in the dispatch thread. –Programs whose GUI must be updated as the result of non- AWT events. For example, suppose a long operation is running in a separate thread? You’ll want to show progress in the GUI, but those GUI changes need to be executed in the dispatch thread.

14 2006-08-16Java Threads14 How to run in the event dispatch thread from your thread? Use either invokeLater or invokeAndWait methods of EventQueue. EventQueue.invokeLater(new Runnable() { public void run() { label.setText(percentage + “% complete”); } }); The invokeLater method returns immediately when the event is posted to the event queue. The invokeAndWait method waits until the run method has completed.

15 2006-08-16Java Threads15 A thread that needs access to GUI state... void printTextField() throws Exception { final String[] myStrings = new String[2]; Runnable getTextFields = new Runnable() { public void run() { myStrings[0] = textField0.getText(); myStrings[1] = textField1.getText(); } }; SwingUtilities.invokeAndWait(getTextFields); System.out.println(myStrings[0] + “ “ + myStrings[1]); }

16 2006-08-16Java Threads16 SwingWorker SwingWorker does all the dirty work of implementing a background thread. To use the SwingWorker class, you first create a subclass of it. In the subclass, you must implement the construct() method so that it contains the code to perform your lengthy operation. You can optionally implement the finish() method to execute code on the event dispatch thread after construct() has finished.

17 2006-08-16Java Threads17 //OLD CODE: public void actionPerformed(ActionEvent e) {... //...code that might take a while to execute... } //BETTER CODE: public void actionPerformed(ActionEvent e) {... final SwingWorker worker = new SwingWorker() { public Object construct() { //...code that might take a while return someValue; } }; worker.start(); // required }

18 public void actionPerformed(ActionEvent e) {... if(icon == null) { // haven’t viewed before loadImage(imagedir + pic.filename, current); } else { updatePhotograph(current, pic); }... // Load an image in a separate thread. private void loadImage(final String imagePath, final int index) { final SwingWorker worker = new SwingWorker() { ImageIcon icon = null; public Object construct() { icon = new ImageIcon(getURL(imagePath)); return icon; } // Runs on the event-dispatching thread public void finished() { Photo pic = (Photo)pictures.elementAt(index); pic.setIcon(icon); if(index == current) updatePhotograph(index, pic); } }; worker.start(); }

19 2006-08-16Java Threads19 Why implement Swing this way? Component developers do not have to have an in-depth understanding of threads programming. Events are dispatched in a predictable order. Runnable objects enqueued by invokeLater() are dispatched from the save event queue as mouse, keyboard, etc... events. Less overhead. Time and effort not spent locking critical areas and synchronizing code.

20 2006-08-16Java Threads20 Thanks for attending.


Download ppt "2006-08-16 Java Threads 1 1 Threading and Concurrent Programming in Java Threads and Swing D.W. Denbo."

Similar presentations


Ads by Google