Using Threads to Maintain Application Liveness


Prerequisites

This Magercise shows how to improve the liveness of a GUI by forking off a new thread to handle a time-consuming task. In this case the task is to fetch a web page.

A simple applet is given as a starting point. It has a text field for entering a URL, a button to get the URL, and a text area for viewing the contents of the fetched URL. The task of fetching the URL can take several seconds, so creating a new thread to handle the fetch process will free the user interface thread to handle other tasks.

Aspects of thread behavior are covered in the course notes section Thread Liveness.

Work Location

Perform all work for this magercise in VisualAge project MageLang Magercises, package magercises.Using Threads to Maintain Application Liveness.

If this project does not appear in your Workspace add it from the repository (if it exists there) or create a new project using this name.

Tasks

Perform the following tasks:

  1. Modify the URLFetchPanel class to be Runnable. Add a variable to the class to hold a Thread.

  2. Modify the action method to create a new Thread, store it in the thread variable and start it. Remove the call to getURL.

  3. Create a run method to do the work of the getURL method. It will replace the getURL method.

  4. Compile and run the applet. To test the URL fetch, type some URL into the text field and press the "Get URL" button. If you are running the applet in a browser, you will probably only be able to fetch a URL from the same site where the applet is loaded from.

The task numbers above are linked to the step-by-step help page. Also available is a complete solution to the problem, and expected behavior, to demonstrate it.

Copyright © 1996-1997 MageLang Institute. All Rights Reserved.