What Is a Thread?
What Is a Thread?
A thread is similar to the sequential programs described previously. A single thread also has a beginning, a sequence, and an end. At any given time during the runtime of the thread, there is a single point of execution. However, a thread itself is not a program; a thread cannot run on its own. Rather, it runs within a program. The following figure shows this relationship.

The real excitement surrounding threads is not about a single sequential thread. Rather, it’s about the use of multiple threads running at the same time and performing different tasks in a single program. This use is illustrated in the next figure.

Some texts call a thread a lightweight process. A thread is similar to a real process in that both have a single sequential flow of control. However, a thread is considered lightweight because it runs within the context of a full-blown program and takes advantage of the resources allocated for that program and the program’s environment.
As a sequential flow of control, a thread must carve out some of its own resources within a running program. For example, a thread must have its own execution stack and program counter. The code running within the thread works only within that context. Some other texts use execution context as a synonym for thread.
Thread programming can be tricky, so if you think you might need to implement threads, consider using high-level thread APIs. For example, if your program must perform a task repeatedly, consider using the java.util.Timer
class. The Timer class is also useful for performing a task after a delay. Examples of its use are in the section Using the Timer and TimerTask Classes
.
If you’re writing a program with a graphical user interface (GUI), you might want to use the javax.swing.Timer
class instead of java.util.Timer. Another utility class, SwingWorker, helps you with another common job: performing a task in a background thread, optionally updating the GUI when the task completes. You can find information about both the Swing Timer class and the SwingWorker class in How to Use Threads
.
Basic support for threads in the Java platform is in the class java.lang.Thread
. It provides a thread API and provides all the generic behavior for threads. (The actual implementation of concurrent operations is system-specific. For most programming needs, the underlying implementation doesn’t matter.) These behaviors include starting, sleeping, running, yielding, and having a priority.
To implement a thread using the Thread class, you need to provide it with a run method that performs the thread's task. The section Implementing the Runnable Interface
tells you how to do this. The next section, The Life Cycle of a Thread
, discusses how to create, start, and stop a thread. The section Thread Scheduling
describes how the Java platform schedules threads and how you can intervene in the scheduling.

Comments
Post a Comment