img
The Thread Class and the Runnable Interface
Java's multithreading system is built upon the Thread class, its methods, and its companion
interface, Runnable. Thread encapsulates a thread of execution. Since you can't directly refer
to the ethereal state of a running thread, you will deal with it through its proxy, the Thread
instance that spawned it. To create a new thread, your program will either extend Thread or
implement the Runnable interface.
The Thread class defines several methods that help manage threads. The ones that will
be used in this chapter are shown here:
Method
Meaning
getName
Obtain a thread's name.
getPriority
Obtain a thread's priority.
isAlive
Determine if a thread is still running.
join
Wait for a thread to terminate.
run
Entr y point for the thread.
sleep
Suspend a thread for a period of time.
star t
Star t a thread by calling its run method.
Thus far, all the examples in this topic have used a single thread of execution. The remainder of
this chapter explains how to use Thread and Runnable to create and manage threads,
beginning with the one thread that all Java programs have: the main thread.
The Main Thread
When a Java program starts up, one thread begins running immediately. This is usually
called the main thread of your program, because it is the one that is executed when your
program begins. The main thread is important for two reasons:
· It is the thread from which other "child" threads will be spawned.
· Often, it must be the last thread to finish execution because it performs various
shutdown actions.
Although the main thread is created automatically when your program is started, it can
be controlled through a Thread object. To do so, you must obtain a reference to it by calling
the method currentThread( ), which is a public static member of Thread. Its general form is
shown here:
static Thread currentThread( )
This method returns a reference to the thread in which it is called. Once you have a reference
to the main thread, you can control it just like any other thread.
Let's begin by reviewing the following example:
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks
Home