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

Slides:



Advertisements
Similar presentations
Concurrency (p2) synchronized (this) { doLecture(part2); } synchronized (this) { doLecture(part2); }
Advertisements

Java Applets- Using SwingWorker Dave Price and Chris Loftus Computer Science Department University of Wales, Aberystwyth.
1 Threads (Extra Lecture) Developing MultiThreaded Application (Part III) Overview  Waiting for Synchronized Data.  Creating Thread Groups.  Daemon.
Multi-threaded applications SE SE-2811 Dr. Mark L. Hornick 2 What SE1011 students are told… When the main() method is called, the instructions.
Object Oriented Programming with Java (150704).   Applet  AWT (Abstract Window Toolkit)  Japplet  Swing Types of Applet.
Slides prepared by Rose Williams, Binghamton University Chapter 17 Swing I.
Review of Java Applets Vijayan Sugumaran Decision and Information Sciences Oakland University.
Cosc 4755 Phone programming: GUI Concepts & Threads.
Threads A thread is a program unit that is executed independently of other parts of the program A thread is a program unit that is executed independently.
Object Oriented Programming Java 1 GUI example taken from “Computing Concepts with Java 2” by Cay Horstmann GUI Programming.
Multithreading in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Threads and GUIs Confession: I’ve never liked GUI programming very much – so I haven’t done a lot of it  I don’t like the visual design aspects  But.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L20 (Chapter 24) Multithreading.
1 Advanced Computer Programming Concurrency Multithreaded Programs Copyright © Texas Education Agency, 2013.
Applets, AWTS CompSci 230 Software Construction.
ACM/JETT Workshop - August 4-5, ExceptionHandling and User Interfaces (Event Delegation, Inner classes) using Swing.
EE2E1. JAVA Programming Lecture 8 Multi-threading.
Java Programming, 3e Concepts and Techniques Chapter 3 Section 65 – Manipulating Data Using Methods – Java Applet.
Welcome to CIS 083 ! Events CIS 068.
1 Event Driven Programming wirh Graphical User Interfaces (GUIs) A Crash Course © Rick Mercer.
Networking: Part 2 (Accessing the Internet). The UI Thread When an application is launched, the system creates a “main” UI thread responsible for handling.
CS12420 – Swing and threads Lynda Thomas
Week 3, Day 1: Processes & Threads Return Quiz Processes Threads Lab: Quiz Lab 3: Strategy & Factory Patterns! SE-2811 Slide design: Dr. Mark L. Hornick.
עקרונות תכנות מונחה עצמים תרגול 4 - GUI. Outline  Introduction to GUI  Swing  Basic components  Event handling.
GUI programming Graphical user interface-based programming.
BI-SW Training day Outline What is the EDT? Why should I care about it? How do I treat GUI objects properly? SwingWorker and its advantages.
Week 3, Day 1: Processes & Threads Processes Threads SE-2811 Slide design: Dr. Mark L. Hornick Content: Dr. Hornick Errors: Dr. Yoder 1.
Java Threads. What is a Thread? A thread can be loosely defined as a separate stream of execution that takes place simultaneously with and independently.
1 GUI programming with threads. 2 Threads and Swing Swing is not generally thread-safe: most methods are not synchronized –correct synchronization is.
1 Web Based Programming Section 8 James King 12 August 2003.
CSC 205 – Java Programming II Applet. Types of Java Programs Applets Applications Console applications Graphics applications Applications are stand-alone.
Swing GUI Components You can create graphics components to place on your applet using classes available in the Swing package ( javax.swing ) Class names.
Concurrent Programming and Threads Threads Blocking a User Interface.
Keeping your Swing Applications Responsive using FoxTrot and Friends Rob Ratcliff.
Introduction to Computation and Problem Solving Class 34: Introduction to Threads Prof. Steven R. Lerman and Dr. V. Judson Harward.
1 Object Oriented Programming Lecture XII Multithreading in Java, A few words about AWT and Swing, The composite design pattern.
Creating a GUI with JFC/Swing. What are the JFC and Swing? JFC –Java Foundation Classes –a group of features to help people build graphical user interfaces.
UID – Event Handling and Listeners Boriana Koleva
Intro to Applets. Applet Applets run within the Web browser environment Applets bring dynamic interaction and live animation to an otherwise static HTML.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Multithreading [Modified]
CIS Intro to JAVA Lecture Notes Set July-05 GUI Programming – Home and reload buttons for the webbrowser, Applets.
Advanced Concurrency Topics Nelson Padua-Perez Bill Pugh Department of Computer Science University of Maryland, College Park.
Threads II IS Outline  Quiz  Thread review  Stopping a thread  java.util.Timer  Swing threads javax.swing.Timer  ProgressMonitor.
Graphics in Java Dr. Andrew Wallace PhD BEng(hons) EurIng
1 GUI programming Graphical user interface-based programming Chapter G1 (pages )
Before class… 下禮拜一交 Proposal – 至多四人一組, 同組同分 – 請勿超過一張 A4 評分標準 創意 技術難度 實用性 User-defined 完整性.
CSC Multiprocessor Programming, Spring, 2011 Chapter 9 – GUI Applications Dr. Dale E. Parson, week 11.
Creating a GUI Class An example of class design using inheritance and interfaces.
Threads in Java Threads Introduction: After completing this chapter, you will be able to code your own thread, control them efficiently without.
Slides prepared by Rose Williams, Binghamton University Chapter 20 Java Never Ends.
Event Handling and Listeners in SWING The practice of event handling.
Swing GUI Components So far, we have written GUI applications which can ‘ draw ’. These applications are simple, yet typical of all Java GUI applications.
Graphical User Interface (GUI)
Threads b A thread is a flow of control in a program. b The Java Virtual Machine allows an application to have multiple threads of execution running concurrently.
5-1 GUIs and Events Rick Mercer. 5-2 Event-Driven Programming with Graphical user Interfaces  Most applications have graphical user interfaces to respond.
Event Driven (Asynchronous) Programming. Event handling in Unity Subclass a class that contains event handling methods, and then override those methods.
Threads and Swing Multithreading. Contents I. Simulation on Inserting and Removing Items in a Combo Box II. Event Dispatch Thread III. Rules for Running.
Lecture 15 Basic GUI programming
Slide design: Dr. Mark L. Hornick
CSC Multiprocessor Programming, Spring, 2012
SE-2811 Software Component Design
Lecture 28 Concurrent, Responsive GUIs
Chapter 19 Java Never Ends
Threads II IS
Constructors, GUI’s(Using Swing) and ActionListner
9. Threads SE2811 Software Component Design
Using threads for long running tasks.
9. Threads SE2811 Software Component Design
Slide design: Dr. Mark L. Hornick
9. Threads SE2811 Software Component Design
Presentation transcript:

Java Threads 1 1 Threading and Concurrent Programming in Java Threads and Swing D.W. Denbo

Java 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.

Java Threads3 Outline “Single Thread” Rule Exceptions to the rule Event dispatching A Swing Worker

Java Threads4 SwingThreadTest

Java 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.

Java 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.

Java 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.

Java 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

Java 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... }

Java 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

Java 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.

Java 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.

Java 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.

Java 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.

Java 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]); }

Java 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.

Java 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 }

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

Java 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.

Java Threads20 Thanks for attending.