How Java Uses Threads

Java applications and applets are naturally threaded. The runtime environment starts execution of the program with the main() method in one thread. Garbage collection takes place in another thread. Screen updating occurs in a third thread. There may be other threads running as well, mostly related to the behavior of the virtual machine. All of this happens invisibly to the programmer. Some of the time you're only concerned with what happens in the primary thread which includes the main() method of a program. If this is the case you may not need to worry about threading at all.

Sometimes, however, you need to add your own threads to an applet or application. The simplest reason for adding a separate thread is to perform a long calculation. For instance if you're trying to find the ten millionth prime number, you probably don't want to make users twiddle their thumbs while you search. Or you may be waiting for a resource that isn't available yet, a large graphic to download from the Internet, for example. Once again you shouldn't make the user wait while your program waits. Any operation that is going to take a noticeable period of time should be placed in its own thread.

The other reason to use threading is to more evenly divide the computer's power among different tasks. If you want to draw random rectangles on the display, you would still like the applet to respond to user input. If all the CPU time is spent drawing rectangles, there's nothing left over for the user. On a preemptively multitasking operating system like Solaris or Windows NT, the user may at least be able to kill the application. On a cooperatively multitasking operating system like MacOS 9 or Windows 9x, the user may have to reboot their machine. This is a bad thing. With threads you can set the priority of different processes, so that user input receives a high priority and drawing pretty pictures receives a low priority. Then the user can stop the applet without flipping the power switch on their machine.

Previous | Next | Top | Cafe au Lait

Copyright 1997, 1998, 2006 Elliotte Rusty Harold
Last Modified August 22, 2006