Thread Class
Package: java.lang
The Thread
class lets you create an object that can be run as a thread in a multithreaded Java application.
Note that an alternative to using the Thread
class to crate multithreaded applications is to use the Runnable
interface. For more information, see Runnable Interface.
Constructors
Constructor |
Description |
|
Creates an instance of the |
|
Creates a |
|
Turns any object that implements an API interface called |
|
Creates a thread from any object that implements |
Methods
Method |
Description |
|
Returns the number of active threads. |
|
Fills the specified array with a copy of each active thread. The return value is the number of threads added to the array. |
|
Returns the name of the thread. |
|
Returns the thread’s priority. |
|
Interrupts this thread. |
|
Checks whether the thread has been interrupted. |
|
Sets the thread’s priority. |
|
Sets the thread’s name. |
|
Causes the currently executing thread ( |
|
Is called when the thread is started. Place the code that you want the thread to execute inside this method. |
|
Starts the thread. |
|
Causes the currently executing thread to yield to other threads that are waiting to execute. |
Extending the Thread class
The easiest way to create a thread is to write a class that extends the Thread
class. Then all you have to do to start a thread is create an instance of your thread class and call its start
method.
A class that extends Thread
should include a run
method. The run
method is automatically called when the thread is started. Note that the run
method must either call sleep
or yield
to give other threads a chance to execute.
Here’s an example of a program that extends the Thread
class and counts down the numbers 20 to 1 at one-second intervals:
public class CountDownClock extends Thread
{
public void run()
{
for (int t = 20; t >= 0; t--)
{
System.out.println (t);
try
{
Thread.sleep(1000);
}
catch (InterruptedException e)
{}
}
}
}
Creating and starting a thread
After you define a class that defines a Thread
object, you can create and start the thread. Here’s a program that launches the CountDownClock
thread shown in the preceding section:
public class CountDownApp
{
public static void main(String[] args)
{
Thread clock = new CountDownClock();
clock.start();
}
}
In this example, a variable of type Thread
is declared, and an instance of the CountDownClock
is created and assigned to it. This creates a Thread
object, but the thread doesn’t begin executing until you call its start
method.