img
Let's look more closely at the methods defined by Thread that are used in the program.
The sleep( ) method causes the thread from which it is called to suspend execution for the
specified period of milliseconds. Its general form is shown here:
static void sleep(long milliseconds) throws InterruptedException
The number of milliseconds to suspend is specified in milliseconds. This method may throw
an InterruptedException.
The sleep( ) method has a second form, shown next, which allows you to specify the
period in terms of milliseconds and nanoseconds:
static void sleep(long milliseconds, int nanoseconds) throws InterruptedException
This second form is useful only in environments that allow timing periods as short as
nanoseconds.
As the preceding program shows, you can set the name of a thread by using setName( ).
You can obtain the name of a thread by calling getName( ) (but note that this is not shown in
the program). These methods are members of the Thread class and are declared like this:
final void setName(String threadName)
final String getName( )
Here, threadName specifies the name of the thread.
Creating a Thread
In the most general sense, you create a thread by instantiating an object of type Thread.
Java defines two ways in which this can be accomplished:
You can implement the Runnable interface.
You can extend the Thread class, itself.
The following two sections look at each method, in turn.
Implementing Runnable
The easiest way to create a thread is to create a class that implements the Runnable interface.
Runnable abstracts a unit of executable code. You can construct a thread on any object that
implements Runnable. To implement Runnable, a class need only implement a single method
called run( ), which is declared like this:
public void run( )
Inside run( ), you will define the code that constitutes the new thread. It is important to
understand that run( ) can call other methods, use other classes, and declare variables, just
like the main thread can. The only difference is that run( ) establishes the entry point for
another, concurrent thread of execution within your program. This thread will end when
run( ) returns.
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks
Home