Previous | Next | Trail Map | Writing Applets | Overview of Applets


Threads in Applets

[TALK ABOUT THREAD GROUPS!]

Note: This page assumes that you know what a thread is. If you don't, read What Are Threads? before reading this page.

Every applet can run in multiple threads. For example, when the HotJava browser first views a document that contains an applet, the browser's DocumentSwitcher thread executes the applet's init() method. And when the user scrolls the document, the AWT WServer thread executes the applet's update() method.

So why would an applet need to create and use its own threads? Imagine an applet that performs some time-consuming initialization -- loading images, for example -- in its init() method. The thread that invokes init() can't do anything else until init() returns. In the HotJava browser, this means that the browser can't display the applet or anything after it until the applet has finished initializing itself. So if the applet is at the top of the page, for example, then nothing will appear on the page until the applet has finished initializing itself.

The solution to this problem is for the applet to create a thread and move the initialization code from the init() method into the thread body. Look at the next page to see both the problem and its cure.


Rule of Thumb: If an applet performs a time-consuming task, it should create and use its own thread to perform that task.

Here is SimpleApplet modified to print the thread that each of its major methods is called from:

If you're using an alpha version of the HotJava browser, view this applet's output using the standard output, since the output doesn't scroll in this page. The beta version of the applet scrolls, making it possible to view the output in your applet viewer (although standard output is still necessary for viewing output caused by reloading the applet).


Previous | Next | Trail Map | Writing Applets | Overview of Applets