Understanding Threads
A thread is a single sequence of executable code within a larger program. All the programs shown so far in this book have used just one thread — the main thread that starts automatically when you run the program. However, Java lets you create programs that start additional threads to perform specific tasks.
Understanding the Thread class
The Thread class lets you create an object that can be run as a thread in a multi-threaded Java application. The Thread class has quite a few constructors and methods, but for most applications you only need to use the ones listed in Table.
Constructors and Methods of the Thread Class
Constructor Explanation
Thread() The basic Thread constructor without
parameters. This constructor simply creates
an instance of the Thread class.
Thread(String name) Creates a Thread object and assigns
the specified name to the thread.
Thread(Runnable target) A more advanced constructor that lets
you turn any object that implements an
API interface called Runnable into a
thread. You see how this constructor is
used later in this chapter.
Thread(Runnable target, Creates a thread from any object that
String name) implements Runnable and assigns the
specified name to the thread.
static int activeCount() Returns the number of active threads.
static int enumerate Fills the specified array with a copy of
(Thread[] t) each active thread. The return value is
the number of threads added to the array.
String getName() Returns the name of the thread.
int getPriority() Returns the thread’s priority.
void interrupt() Interrupts this thread.
boolean isInterrupted() Checks to see if the thread has been
interrupted.