Unraveling threads

Multi-threaded programming offers developers substantial advantages, and
users increased performance. Despite the obvious benefits, novice programmers
are reluctant to write multi-threaded applications because of their perceived
complexity. This article will offer a gentle introduction to multi-threaded
programming. -- David Reilly

So, what exactly are threads?

Threads are multiple instances of an application or applet that execute
concurrently.

Woah! That's a mouthful isn't it. Let's break it down a little.

When we start an application, it executes in its own process - it has its own
chunk of memory for data storage, and it runs alongside other processes. Modern
operating systems (such as Windows, and Unix) create the illusion that these
processes are running concurrently. A process can execute at the same time as
another process, and the operating shares time between all running processes
(though not always evenly). Each process represents a single thread of
execution.

Now a multi-threaded application is a special kind of application. It uses
only a single process, but that process has multiple threads of execution. The
same code and data is used, but we have more than one instance of the
application running. Each thread runs concurrently, so when one thread is idle
(perhaps waiting for data input), another thread can be performing some useful
task. Easy huh?

What can threads do?

Threads are extremely useful, because they allow developers to write
applications that are more responsive to the user. When your application is
processing data, its poor design for the user-interface to be disabled until the
task is complete. If your application is single-threaded, the user-interface
can't respond to user commands if the application is performing another task.
Furthermore, applications can their idle time to process things behind the
scenes. For example, an applet that displays some animation can be preparing the
next frame.

So how do I use threads?

Threads are actually quite easy to use, provided you do a little planning.
First you have to identify the tasks a thread will perform. Usually your
thread(s) will perform processing, allowing your primary thread to handle
user-interface events. Once you've identified a task, you have to write the code
for your thread.

Our example will be an applet that displays a simple text scrolling
animation. We'll create a new thread to create the animation, leaving our
application free to respond to the user interface. Our applet will respond to
two user-interface events : mouseDown and mouseUp.

Example 1.0 - Animated applet with
multiple threads

When a user clicks on the applet, animation stops. When the mouse button is
released, the animation resumes. Other than these two actions, all our applet
does is launch a second thread to perform the animation. Let's look at the
thread specific code.

Creating a new thread

Creating a new thread is pretty simple, and takes only a few lines of code.
In our example, the new thread is created in the applet's start() method. We
first check to see if an animation thread is already running, and if not, create
one.

Notice the parameter we use when creating a new Thread object. This form of
constructor accepts an instance of java.lang.Runnable, which is an interface our
applet implements. We'll see how this works later, but for those who are
curious, it is an interface that indicates our applet has work a thread can
perform. We use the this keyword to indicate that
the current class/object is being referred to.

Next, we call that thread's start method. Once started, a thread will execute
independently, until it completes its task, or the thread is suspended or
stopped. Here's the full code for our start method.

Putting threads to work

When a thread is started, it calls the run() method of the class implementing
the java.lang.Runnable interface. That means that we need to write a run()
method to get our thread to perform useful work, as well as indicating in our
class declaration that our applet will implement the interface.

Here's the change we need to make to a class declaration (change in bold). We
simple add the implements keyword, and indicate the interface that is
implemented.

public class AnimationApplet extends
Applet implements Runnable

Finally, we need to write a run() method for our thread runnable class. Your
run method must be public, and should contain the code you want the thread to
execute. When the run method completes, the thread will stop - so make sure your
run() method contains a loop of some kind so that it can continue to perform
useful work.

while (true)
{try
{
// Create the next frame of animation
................

repaint();
Thread.sleep(10);

}catch (InterruptedException
e)
{
stop();
}
}
}

Most of the work performed in this particular run() method is not related to
the topic of threads, but feel free to examine the source in more detail if
you're interested. One important point that must be made is that our thread
tries not to consume all available CPU resources. Our thread, when it has
created the next animation frame, goes to sleep. The JVM will, most likely,
allocate a fair share of CPU time to each thread, but in the event it does not,
our thread will sleep. Unless your thread is extremely important, its probably a
good idea to be considerate of other application threads.

Summary

Writing multi-threaded applications need not be a difficult or mysterious
task. Simply create a new class that implements the java.lang.Runnable class, or
implement it in your application/applets class. Then, pass it as a parameter to
a thread constructor, and start the thread. Voila! Instant threads.