Recent articles:
Popular archives:
Java: A platform for platforms
Sun's reorg may seem promising to shareholders but it's also a scramble for position. The question now is whether Sun can,
or wants to, maintain its hold on Java technology. Especially with enterprise leaders like SpringSource and RedHat investing
heavily in Java's future as a platform for platforms
Also see:
Discuss: Tim Bray on 'What Sun Should Do'
Users hate unresponsive software. When users click a mouse, they expect a program to instantly respond to their requests, even when the program is in the midst of a time-consuming activity, such as repaginating a long document or waiting for a network operation to complete. Programs that respond slowly to their users exhibit poor performance. To improve a program's performance, developers typically use threads.
This article is the first in a four-part series that explores threads. Although you might think threads a difficult subject
to grasp, I intend to show you that threads are easy to understand. In this article, I introduce you to threads and the Thread class, and discuss runnables. Furthermore, the accompanying sidebar, "Exceptions and the run() Method" discusses exceptions in the context of a thread object's run() method. In subsequent articles, I will explore synchronization (via locks), synchronization problems (such as deadlock),
the wait/notify mechanism, scheduling (with and without priority), thread interruption, timers, volatility, thread groups,
and thread local variables.
Read the whole series on thread programming:
| Note |
|---|
| This article and its three companions examine threads in the context of applications, as opposed to applets. However, much of what I present in the application context applies to applets. The main difference: For security reasons, not all thread operations are possible within an applet (I will discuss applets in a future article). |
Conceptually, the notion of a thread is not difficult to grasp: it's an independent path of execution through program code. When multiple threads execute, one
thread's path through the same code usually differs from the others. For example, suppose one thread executes the byte code
equivalent of an if-else statement's if part, while another thread executes the byte code equivalent of the else part. How does the JVM keep track of each thread's execution? The JVM gives each thread its own method-call stack. In addition
to tracking the current byte code instruction, the method-call stack tracks local variables, parameters the JVM passes to
a method, and the method's return value.
When multiple threads execute byte-code instruction sequences in the same program, that action is known as multithreading. Multithreading benefits a program in various ways:
Java accomplishes multithreading through its java.lang.Thread class. Each Thread object describes a single thread of execution. That execution occurs in Thread's run() method. Because the default run() method does nothing, you must subclass Thread and override run() to accomplish useful work. For a taste of threads and multithreading in the context of Thread, examine Listing 1:
Listing 1. ThreadDemo.java
// ThreadDemo.java
class ThreadDemo
{
public static void main (String [] args)
{
MyThread mt = new MyThread ();
mt.start ();
for (int i = 0; i < 50; i++)
System.out.println ("i = " + i + ", i * i = " + i * i);
}
}
class MyThread extends Thread
{
public void run ()
{
for (int count = 1, row = 1; row < 20; row++, count++)
{
for (int i = 0; i < count; i++)
System.out.print ('*');
System.out.print ('\n');
}
}
}
Listing 1 presents source code to an application consisting of classes ThreadDemo and MyThread. Class ThreadDemo drives the application by creating a MyThread object, starting a thread that associates with that object, and executing some code to print a table of squares. In contrast,
MyThread overrides Thread's run() method to print (on the standard output stream) a right-angle triangle composed of asterisk characters.
When you type java ThreadDemo to run the application, the JVM creates a starting thread of execution, which executes the main() method. By executing mt.start ();, the starting thread tells the JVM to create a second thread of execution that executes the byte code instructions comprising
the MyThread object's run() method. When the start() method returns, the starting thread executes its for loop to print a table of squares, while the new thread executes the run() method to print the right-angle triangle.
What does the output look like? Run ThreadDemo to find out. You will notice each thread's output tends to intersperse with the other's output. That results because both
threads send their output to the same standard output stream.
| Note |
|---|
| Most (if not all) JVM implementations use the underlying platform's threading capabilities. Because those capabilities are platform-specific, the order of your multithreaded programs' output might differ from the order of someone else's output. That difference results from scheduling, a topic I explore later in this series. |
To grow proficient at writing multithreaded code, you must first understand the various methods that make up the Thread class. This section explores many of those methods. Specifically, you learn about methods for starting threads, naming threads,
putting threads to sleep, determining whether a thread is alive, joining one thread to another thread, and enumerating all
active threads in the current thread's thread group and subgroups. I also discuss Thread's debugging aids and user threads versus daemon threads.
I'll present the remainder of Thread's methods in subsequent articles, with the exception of Sun's deprecated methods.
| Caution |
|---|
Sun has deprecated a variety of Thread methods, such as suspend() and resume(), because they can lock up your programs or damage objects. As a result, you should not call them in your code. Consult the
SDK documentation for workarounds to those methods. I do not cover deprecated methods in this series.
|
Thread has eight constructors. The simplest are:
Thread(), which creates a Thread object with a default name
Thread(String name), which creates a Thread object with a name that the name argument specifies
The next simplest constructors are Thread(Runnable target) and Thread(Runnable target, String name). Apart from the Runnable parameters, those constructors are identical to the aforementioned constructors. The difference: The Runnable parameters identify objects outside Thread that provide the run() methods. (You learn about Runnable later in this article.) The final four constructors resemble Thread(String name), Thread(Runnable target), and Thread(Runnable target, String name); however, the final constructors also include a ThreadGroup argument for organizational purposes.