Threads and Swing Multithreading. Contents I. Simulation on Inserting and Removing Items in a Combo Box II. Event Dispatch Thread III. Rules for Running.

Slides:



Advertisements
Similar presentations
Chapter 8 Improving the User Interface
Advertisements

Concurrency (p2) synchronized (this) { doLecture(part2); } synchronized (this) { doLecture(part2); }
Threads Section 2.2. Introduction to threads A thread (of execution) is a light-weight process –Threads reside within processes. –They share one address.
© The McGraw-Hill Companies, 2006 Chapter 18 Advanced graphics programming.
WORKING WITH MACROS CHAPTER 10 WORKING WITH MACROS.
Microsoft Visual Basic 2012 Using Procedures and Exception Handling CHAPTER SEVEN.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Concurrency in Android with.
Nachos Phase 1 Code -Hints and Comments
Networking: Part 2 (Accessing the Internet). The UI Thread When an application is launched, the system creates a “main” UI thread responsible for handling.
Copyright © 2007, Oracle. All rights reserved. Managing Concurrent Requests.
Chapter 12: How Long Can This Go On?
1 GUI programming with threads. 2 Threads and Swing Swing is not generally thread-safe: most methods are not synchronized –correct synchronization is.
Concurrent Programming and Threads Threads Blocking a User Interface.
CS378 - Mobile Computing Responsiveness. An App Idea From Nifty Assignments Draw a picture use randomness Pick an equation at random Operators in the.
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition.
CS324e - Elements of Graphics and Visualization Java GUIs - Event Handling.
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
Before class… 下禮拜一交 Proposal – 至多四人一組, 同組同分 – 請勿超過一張 A4 評分標準 創意 技術難度 實用性 User-defined 完整性.
(1) Introduction to Java GUIs Philip Johnson Collaborative Software Development Laboratory Information and Computer Sciences University of Hawaii Honolulu.
CSC Multiprocessor Programming, Spring, 2011 Chapter 9 – GUI Applications Dr. Dale E. Parson, week 11.
JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch ISBN © 2012 Pearson Education, Inc., Upper Saddle River,
Java Threads 1 1 Threading and Concurrent Programming in Java Threads and Swing D.W. Denbo.
Review IS Overview: Data  Inside the application Collections  Outside the application Database XML  Getting/displaying Swing  Communicating.
12-Jun-16 Event loops. 2 Programming in prehistoric times Earliest programs were all “batch” processing There was no interaction with the user Input Output.
CHAPTER 6 Threads, Handlers, and Programmatic Movement.
Sending . Contents A)Sending Mail Using Command Line B)Sending Mail Using GUI.
The Echo Server Problem. Contents  Basic Networking Concepts  The Echo Server Problem.
The Echo Server Problem. Contents  Basic Networking Concepts  The Echo Server Problem.
Synchronization (Threads Accessing Shared Data). Contents I.The Bank Transfer Problem II.Doing a Simulation on the Bank Transfer Problem III.New Requirement:
Internationalization The Number Format Problem
Section 10.1 Define scripting
The Bouncing Ball Problem (Independent Threads)
Christopher Budo, Davis Nygren, spencer franks, Luke miller
Visual Basic Code & No.: CS 218
Event loops 16-Jun-18.
CONTENT MANAGEMENT SYSTEM CSIR-NISCAIR, New Delhi
CSC Multiprocessor Programming, Spring, 2012
An Introduction to Computers and Visual Basic
Section 64 – Manipulating Data Using Methods – Java Swing
Lecture 27 Creating Custom GUIs
Process Management Presented By Aditya Gupta Assistant Professor
Singleton Pattern Command Pattern
More About Threads.
Lecture 28 Concurrent, Responsive GUIs
Chapter 19 Java Never Ends
An Introduction to Computers and Visual Basic
Using Procedures and Exception Handling
Predefined Dialog Boxes
Event loops.
COMMON CONTROLS A control is a child window that an application uses in conjunction with another window to enable user interaction. Controls are most often.
CS371m - Mobile Computing Responsiveness.
CIS 16 Application Development Programming with Visual Basic
Android Topics UI Thread and Limited processing resources
Android Topics Asynchronous Callsbacks
Event loops 17-Jan-19.
Event loops 17-Jan-19.
Android Topics Threads and the MessageQueue
An Introduction to Computers and Visual Basic
Prepare a DD Form 1081-Return
Constructors, GUI’s(Using Swing) and ActionListner
Chapter 3: Processes.
Chapter 4: Threads.
Event loops 8-Apr-19.
Using threads for long running tasks.
Exception and Event Handling
Outline Chapter 2 (cont) Chapter 3: Processes Virtual machines
Event loops.
Event loops 19-Aug-19.
Presentation transcript:

Threads and Swing Multithreading

Contents I. Simulation on Inserting and Removing Items in a Combo Box II. Event Dispatch Thread III. Rules for Running Time-Consuming Tasks IV. The Reading Text File Problem

I. Simulation on Inserting and Removing Items in a Combo Box Develop a GUI program to insert/remove an item (a positive integer) to/from a combo box continuously and randomly in a separate thread A sample GUI is below  As long as the button is clicked, the simulation runs

Solution 1. Developing a Non-Thread-Safe Solution 2. Observing the Problem 3. Correcting the Problem

1. Developing a Non-Thread-Safe Solution 1.1. The Main Class 1.2. Developing the View 1.3. Adding Listener to the Button

1.1. The Main Class

1.2. Developing the View

1.3. Adding Listener to the Button

2. Observing the Problem Click the Remove/Insert button > Click the combo box a few times > Move the scrollbar > Move the window > Click the Remove/Insert button again > Keep clicking the combo box > Eventually, you should see an exception report What is going on?  When an element is inserted into the combo box, the combo box fires an event to update the display  Then, the display code springs into action, reading the current size of the combo box and preparing to display the values  But the worker thread keeps going - occasionally resulting in a reduction of the count of the values in the combo box. The display code then thinks that there are more values in the model than there actually are, asks for nonexistent values, and triggers an ArrayIndexOutOfBounds exception

3. Correcting the Problem: Put the Updating GUI Code to the Event Dispatch Thread

II. Event Dispatch Thread The thread of control that passes events such as mouse clicks and keystrokes to the user interface components  Every Java application starts with a main method that runs in the main thread  In a Swing program, the main thread is short-lived. It schedules the construction of the user interface in the event dispatch thread and then exits  The event dispatch thread keeps the program alive until it is terminated, either by closing the frame or by calling the System.exit method

III. Rules for Running Time-Consuming Tasks If an action takes a long time, do it in a separate worker thread and never in the event dispatch thread. Do not touch Swing components in any thread other than the event dispatch thread by using EventQueue.invokeLater() or EventQueue.invokeAndWait()  The invokeLater method returns immediately when the event is posted to the event queue  The invokeAndWait method waits until the run method has actually been executed

IV. The Reading Text File Problem Develop a program for loading a text file and for canceling the file loading process Since we want to be able to load big files, a separate thread should be used for loading While the file is read, the Open menu item is disabled and the Cancel item is enabled (see the next slide) After each line is read, a line counter in the status bar is updated After the reading process is complete, the Open menu item is reenabled, the Cancel item is disabled, and the status line text is set to Done

Solution 1. Developing the View 2. Adding Listeners to the Menu Items

1. Developing the View

2. Adding Listeners to the Menu Items 2.1. Adding Listener to the Open Menu Item 2.2. Adding Listener to the Cancel Menu Item

2.1 Adding Listener to the Open Menu Item Getting the Selected File Showing Content in the Selected File

2.1.1 Getting the Selected File

2.1.2 Showing Content in the Selected File A Single-Threading Version A Multiple-Threading Version

A Single-Threading Version

A Multiple-Threading Version Using SwingWorker Defining Result Type and Progress Data Type Developing the Text Reading Thread

Using SwingWorker The typical UI activities of a background task:  After each work unit, update the UI to show progress.  After the work is finished, make a final change to the UI. The SwingWorker class makes it easy to implement such a task.

Using SwingWorker Since the reading process can take a long time, we use the SwingWorker class to fire up a new thread to do the work SwingWorker(T, V)  T: Final result of type T  V: Intermediate progress data of type V

Using SwingWorker Override the doInBackground method to do the time-consuming work  The doInBackground method is executed in a worker thread.  In the doInBackground method, occasionally call publish method to communicate work progress. The publish method causes a process method to execute in the event dispatch thread to deal with the progress data.

When the work is complete, the done method is called in the event dispatch thread so that we can finish updating the UI. To cancel the work in progress, use the cancel method.  When the work is canceled, the get method throws a CancellationException.

Event Dispatch ThreadWorker Thread swObj.execute()swObj.doInBackground() Do the job swObj.publish() swObj.process() swObj.done() The get() does not throw a CancellationException

Defining Final Result Type and Progress Data Type Final Result Type  String, but StringBuilder would be more efficient for big files Progress Data Type: The Current Line

Developing the Text Reading Thread

Developing doInBackground() for Carrying out the Task

Developing process() for Processing Progress Data in the Event Dispatch Thread

Developing done()

2.2. Adding Listener to the Cancel Menu Item

Run the program and try to click Cancel

Ignore the exception message

References 1. Core Java, Volume I - Fundamentals, Eighth Edition, Chapter 14. Cay S. Horstmann and Gary Cornell. Prentice Hall, 2008