Previous | Next | Trail Map | Writing Applets | The Anatomy of an Applet


Threads in Applets: Example

Note: If you've already looked at this page, reload it to see the example again.

Another note: This example was designed for the 1.0 Alpha 3 HotJava browser with immediate applet loading. It might not make sense when viewed any other way. You can't predict the thread architecture of every browser -- one might spin off a separate thread for every applet, while another might use fewer threads than the HotJava browser uses. The safest thing to do is to follow this rule: Create a separate thread to perform any lengthy operation.

The following applet (named Good) has a computation-intensive beginning sequence, implemented as a loop that occasionally prints status. The Good applet does the right thing: Instead of putting the loop in the init() or start() method, it spins off a thread to do the computation. (Here's the source code.) Notice how relatively quickly the browser can display the applet and the text after it.

The next applet (named Bad) does the same things as Good, but at the wrong time: It performs its computation in its init() method. (Here's the source code.) You can watch the applet's progress by reading the status line at the bottom of this window. Notice how the applet and the text that follows it don't appear for quite a while, since the formatting thread is stuck executing the applet's init() method.

Worse yet, the Bad applet starves the Good one. Because the Good applet's start() method doesn't get called until Bad's init() method has returned, the Good applet doesn't get a chance to create its thread (much less run it) until the Bad applet is finished.


Previous | Next | Trail Map | Writing Applets | The Anatomy of an Applet