public class Thread extends Object implements Runnable
Thread
is a concurrent unit of execution. It has its own call stack
for methods being invoked, their arguments and local variables. Each virtual
machine instance has at least one main Thread
running when it is
started; typically, there are several others for housekeeping. The
application might decide to launch additional Thread
s for specific
purposes.
Thread
s in the same VM interact and synchronize by the use of shared
objects and monitors associated with these objects. Synchronized methods and
part of the API in Object
also allow Thread
s to cooperate.
There are basically two main ways of having a Thread
execute
application code. One is providing a new class that extends Thread
and overriding its run()
method. The other is providing a new
Thread
instance with a Runnable
object during its creation.
In both cases, the start()
method must be called to actually execute
the new Thread
.
Each Thread
has an integer priority that basically determines the
amount of CPU time the Thread
gets. It can be set using the
setPriority(int)
method. A Thread
can also be made a daemon,
which makes it run in the background. The latter also affects VM termination
behavior: the VM does not terminate automatically as long as there are
non-daemon threads running.
Object
,
ThreadGroup
Modifier and Type | Class and Description |
---|---|
static class |
Thread.State
A representation of a thread's state.
|
static interface |
Thread.UncaughtExceptionHandler
Implemented by objects that want to handle cases where a thread is being
terminated by an uncaught exception.
|
Modifier and Type | Field and Description |
---|---|
static int |
MAX_PRIORITY
The maximum priority value allowed for a thread.
|
static int |
MIN_PRIORITY
The minimum priority value allowed for a thread.
|
static int |
NORM_PRIORITY
The normal (default) priority value assigned to threads.
|
Constructor and Description |
---|
Thread()
Constructs a new
Thread with no Runnable object and a
newly generated name. |
Thread(Runnable runnable)
Constructs a new
Thread with a Runnable object and a
newly generated name. |
Thread(Runnable runnable,
String threadName)
Constructs a new
Thread with a Runnable object and name
provided. |
Thread(String threadName)
Constructs a new
Thread with no Runnable object and the
name provided. |
Thread(ThreadGroup group,
Runnable runnable)
Constructs a new
Thread with a Runnable object and a
newly generated name. |
Thread(ThreadGroup group,
Runnable runnable,
String threadName)
Constructs a new
Thread with a Runnable object, the given
name and belonging to the ThreadGroup passed as parameter. |
Thread(ThreadGroup group,
Runnable runnable,
String threadName,
long stackSize)
Constructs a new
Thread with a Runnable object, the given
name and belonging to the ThreadGroup passed as parameter. |
Thread(ThreadGroup group,
String threadName)
Constructs a new
Thread with no Runnable object, the
given name and belonging to the ThreadGroup passed as parameter. |
Modifier and Type | Method and Description |
---|---|
static int |
activeCount()
Returns the number of active
Thread s in the running Thread 's group and its subgroups. |
void |
checkAccess()
Does nothing.
|
int |
countStackFrames()
Deprecated.
The results of this call were never well defined. To make
things worse, it would depend on whether the Thread was
suspended or not, and suspend was deprecated too.
|
static Thread |
currentThread()
Returns the Thread of the caller, that is, the current Thread.
|
void |
destroy()
Deprecated.
Not implemented.
|
static void |
dumpStack()
Prints to the standard error stream a text representation of the current
stack for this Thread.
|
static int |
enumerate(Thread[] threads)
Copies an array with all Threads which are in the same ThreadGroup as the
receiver - and subgroups - into the array
threads passed as
parameter. |
static Map<Thread,StackTraceElement[]> |
getAllStackTraces()
Returns a map of all the currently live threads to their stack traces.
|
ClassLoader |
getContextClassLoader()
Returns the context ClassLoader for this Thread.
|
static Thread.UncaughtExceptionHandler |
getDefaultUncaughtExceptionHandler()
Returns the default exception handler that's executed when uncaught
exception terminates a thread.
|
long |
getId()
Returns the thread's identifier.
|
String |
getName()
Returns the name of the Thread.
|
int |
getPriority()
Returns the priority of the Thread.
|
StackTraceElement[] |
getStackTrace()
Returns an array of
StackTraceElement representing the current thread's stack. |
Thread.State |
getState()
Returns the current state of the Thread.
|
ThreadGroup |
getThreadGroup()
Returns the ThreadGroup to which this Thread belongs.
|
Thread.UncaughtExceptionHandler |
getUncaughtExceptionHandler()
Returns the thread's uncaught exception handler.
|
static boolean |
holdsLock(Object object)
Indicates whether the current Thread has a monitor lock on the specified
object.
|
void |
interrupt()
Posts an interrupt request to this
Thread . |
static boolean |
interrupted()
Returns a
boolean indicating whether the current Thread (
currentThread() ) has a pending interrupt request (
true ) or not (false ). |
boolean |
isAlive()
Returns
true if the receiver has already been started and
still runs code (hasn't died yet). |
boolean |
isDaemon()
Returns a
boolean indicating whether the receiver is a
daemon Thread (true ) or not (false ) A
daemon Thread only runs as long as there are non-daemon Threads running. |
boolean |
isInterrupted()
Returns a
boolean indicating whether the receiver has a
pending interrupt request (true ) or not (
false ) |
void |
join()
Blocks the current Thread (
Thread.currentThread() ) until
the receiver finishes its execution and dies. |
void |
join(long millis)
Blocks the current Thread (
Thread.currentThread() ) until
the receiver finishes its execution and dies or the specified timeout
expires, whatever happens first. |
void |
join(long millis,
int nanos)
Blocks the current Thread (
Thread.currentThread() ) until
the receiver finishes its execution and dies or the specified timeout
expires, whatever happens first. |
void |
parkFor(long nanos)
Parks the current thread for a particular number of nanoseconds, or
indefinitely.
|
void |
parkUntil(long time)
Parks the current thread until the specified system time.
|
void |
popInterruptAction$(Runnable interruptAction)
Removes
interruptAction so it is not invoked upon interruption. |
void |
pushInterruptAction$(Runnable interruptAction)
Adds a runnable to be invoked upon interruption.
|
void |
resume()
Deprecated.
Used with deprecated method
suspend() |
void |
run()
Calls the
run() method of the Runnable object the receiver
holds. |
void |
setContextClassLoader(ClassLoader cl)
Set the context ClassLoader for the receiver.
|
void |
setDaemon(boolean isDaemon)
Set if the receiver is a daemon Thread or not.
|
static void |
setDefaultUncaughtExceptionHandler(Thread.UncaughtExceptionHandler handler)
Sets the default uncaught exception handler.
|
void |
setName(String threadName)
Sets the name of the Thread.
|
void |
setPriority(int priority)
Sets the priority of the Thread.
|
void |
setUncaughtExceptionHandler(Thread.UncaughtExceptionHandler handler)
Sets the uncaught exception handler.
|
static void |
sleep(long time)
Causes the thread which sent this message to sleep for the given interval
of time (given in milliseconds).
|
static void |
sleep(long millis,
int nanos)
Causes the thread which sent this message to sleep for the given interval
of time (given in milliseconds and nanoseconds).
|
void |
start()
Starts the new Thread of execution.
|
void |
stop()
Deprecated.
because stopping a thread in this manner is unsafe and can
leave your application and the VM in an unpredictable state.
|
void |
stop(Throwable throwable)
Deprecated.
because stopping a thread in this manner is unsafe and can
leave your application and the VM in an unpredictable state.
|
void |
suspend()
Deprecated.
May cause deadlocks.
|
String |
toString()
Returns a string containing a concise, human-readable description of the
Thread.
|
void |
unpark()
Unparks this thread.
|
static void |
yield()
Causes the calling Thread to yield execution time to another Thread that
is ready to run.
|
public static final int MAX_PRIORITY
public static final int MIN_PRIORITY
public static final int NORM_PRIORITY
public Thread()
Thread
with no Runnable
object and a
newly generated name. The new Thread
will belong to the same
ThreadGroup
as the Thread
calling this constructor.ThreadGroup
,
Runnable
public Thread(Runnable runnable)
Thread
with a Runnable
object and a
newly generated name. The new Thread
will belong to the same
ThreadGroup
as the Thread
calling this constructor.runnable
- a Runnable
whose method run
will be
executed by the new Thread
ThreadGroup
,
Runnable
public Thread(Runnable runnable, String threadName)
Thread
with a Runnable
object and name
provided. The new Thread
will belong to the same ThreadGroup
as the Thread
calling this constructor.runnable
- a Runnable
whose method run
will be
executed by the new Thread
threadName
- the name for the Thread
being createdThreadGroup
,
Runnable
public Thread(String threadName)
Thread
with no Runnable
object and the
name provided. The new Thread
will belong to the same ThreadGroup
as the Thread
calling this constructor.threadName
- the name for the Thread
being createdThreadGroup
,
Runnable
public Thread(ThreadGroup group, Runnable runnable)
Thread
with a Runnable
object and a
newly generated name. The new Thread
will belong to the ThreadGroup
passed as parameter.group
- ThreadGroup
to which the new Thread
will
belongrunnable
- a Runnable
whose method run
will be
executed by the new Thread
IllegalThreadStateException
- if group.destroy()
has already been doneThreadGroup
,
Runnable
public Thread(ThreadGroup group, Runnable runnable, String threadName)
Thread
with a Runnable
object, the given
name and belonging to the ThreadGroup
passed as parameter.group
- ThreadGroup to which the new Thread
will belongrunnable
- a Runnable
whose method run
will be
executed by the new Thread
threadName
- the name for the Thread
being createdIllegalThreadStateException
- if group.destroy()
has already been doneThreadGroup
,
Runnable
public Thread(ThreadGroup group, String threadName)
Thread
with no Runnable
object, the
given name and belonging to the ThreadGroup
passed as parameter.group
- ThreadGroup
to which the new Thread
will belongthreadName
- the name for the Thread
being createdIllegalThreadStateException
- if group.destroy()
has already been doneThreadGroup
,
Runnable
public Thread(ThreadGroup group, Runnable runnable, String threadName, long stackSize)
Thread
with a Runnable
object, the given
name and belonging to the ThreadGroup
passed as parameter.group
- ThreadGroup
to which the new Thread
will
belongrunnable
- a Runnable
whose method run
will be
executed by the new Thread
threadName
- the name for the Thread
being createdstackSize
- a stack size for the new Thread
. This has a highly
platform-dependent interpretation. It may even be ignored
completely.IllegalThreadStateException
- if group.destroy()
has already been doneThreadGroup
,
Runnable
public static int activeCount()
Thread
s in the running Thread
's group and its subgroups.Thread
spublic final void checkAccess()
@Deprecated public int countStackFrames()
public static Thread currentThread()
@Deprecated public void destroy()
public static void dumpStack()
Throwable.printStackTrace()
public static int enumerate(Thread[] threads)
threads
passed as
parameter. If the array passed as parameter is too small no exception is
thrown - the extra elements are simply not copied.threads
- array into which the Threads will be copiedpublic static Map<Thread,StackTraceElement[]> getAllStackTraces()
public ClassLoader getContextClassLoader()
ClassLoader
,
getContextClassLoader()
public static Thread.UncaughtExceptionHandler getDefaultUncaughtExceptionHandler()
Thread.UncaughtExceptionHandler
or null
if
none exists.public long getId()
long
generated on thread creation, is unique to the thread, and doesn't change
during the lifetime of the thread; the ID may be reused after the thread
has been terminated.public final String getName()
public final int getPriority()
setPriority(int)
public StackTraceElement[] getStackTrace()
StackTraceElement
representing the current thread's stack.public Thread.State getState()
Thread.State
value.public final ThreadGroup getThreadGroup()
public Thread.UncaughtExceptionHandler getUncaughtExceptionHandler()
null
is returned.Thread.UncaughtExceptionHandler
instance or null
.public void interrupt()
Thread
. The behavior depends on
the state of this Thread
:
Thread
s blocked in one of Object
's wait()
methods
or one of Thread
's join()
or sleep()
methods will
be woken up, their interrupt status will be cleared, and they receive an
InterruptedException
.
Thread
s blocked in an I/O operation of an
InterruptibleChannel
will have their interrupt
status set and receive an
ClosedByInterruptException
. Also, the channel
will be closed.
Thread
s blocked in a Selector
will have
their interrupt status set and return immediately. They don't receive an
exception in this case.
interrupted()
,
isInterrupted()
public static boolean interrupted()
boolean
indicating whether the current Thread (
currentThread()
) has a pending interrupt request (
true
) or not (false
). It also has the side-effect of
clearing the flag.boolean
indicating the interrupt statuscurrentThread()
,
interrupt()
,
isInterrupted()
public final boolean isAlive()
true
if the receiver has already been started and
still runs code (hasn't died yet). Returns false
either if
the receiver hasn't been started yet or if it has already started and run
to completion and died.boolean
indicating the liveness of the Threadstart()
public final boolean isDaemon()
boolean
indicating whether the receiver is a
daemon Thread (true
) or not (false
) A
daemon Thread only runs as long as there are non-daemon Threads running.
When the last non-daemon Thread ends, the whole program ends no matter if
it had daemon Threads still running or not.boolean
indicating whether the Thread is a daemonsetDaemon(boolean)
public boolean isInterrupted()
boolean
indicating whether the receiver has a
pending interrupt request (true
) or not (
false
)boolean
indicating the interrupt statusinterrupt()
,
interrupted()
public final void join() throws InterruptedException
Thread.currentThread()
) until
the receiver finishes its execution and dies.InterruptedException
- if interrupt()
was called for
the receiver while it was in the join()
callObject.notifyAll()
,
ThreadDeath
public final void join(long millis) throws InterruptedException
Thread.currentThread()
) until
the receiver finishes its execution and dies or the specified timeout
expires, whatever happens first.millis
- The maximum time to wait (in milliseconds).InterruptedException
- if interrupt()
was called for
the receiver while it was in the join()
callObject.notifyAll()
,
ThreadDeath
public final void join(long millis, int nanos) throws InterruptedException
Thread.currentThread()
) until
the receiver finishes its execution and dies or the specified timeout
expires, whatever happens first.millis
- The maximum time to wait (in milliseconds).nanos
- Extra nanosecond precisionInterruptedException
- if interrupt()
was called for
the receiver while it was in the join()
callObject.notifyAll()
,
ThreadDeath
@Deprecated public final void resume()
suspend()
UnsupportedOperationException
.suspend()
public void run()
run()
method of the Runnable object the receiver
holds. If no Runnable is set, does nothing.public void setContextClassLoader(ClassLoader cl)
cl
- The context ClassLoadergetContextClassLoader()
public final void setDaemon(boolean isDaemon)
isDaemon
- indicates whether the Thread should be daemon or notisDaemon()
public static void setDefaultUncaughtExceptionHandler(Thread.UncaughtExceptionHandler handler)
handler
- The handler to set or null.public final void pushInterruptAction$(Runnable interruptAction)
Each call to this method must be matched with a corresponding call to
popInterruptAction$(java.lang.Runnable)
.
public final void popInterruptAction$(Runnable interruptAction)
interruptAction
so it is not invoked upon interruption.interruptAction
- the pushed action, used to check that the call
stack is correctly nested.public final void setName(String threadName)
threadName
- the new name for the ThreadgetName()
public final void setPriority(int priority)
priority
- new priority for the ThreadIllegalArgumentException
- if the new priority is greater than Thread.MAX_PRIORITY or
less than Thread.MIN_PRIORITYgetPriority()
public void setUncaughtExceptionHandler(Thread.UncaughtExceptionHandler handler)
Sets the uncaught exception handler. This handler is invoked in case this Thread dies due to an unhandled exception.
handler
- The handler to set or null
.public static void sleep(long time) throws InterruptedException
time
- The time to sleep in milliseconds.InterruptedException
- if interrupt()
was called for this Thread while
it was sleepinginterrupt()
public static void sleep(long millis, int nanos) throws InterruptedException
millis
- The time to sleep in milliseconds.nanos
- Extra nanosecond precisionInterruptedException
- if interrupt()
was called for this Thread while
it was sleepinginterrupt()
public void start()
run()
method of
the receiver will be called by the receiver Thread itself (and not the
Thread calling start()
).IllegalThreadStateException
- if the Thread has been started beforerun()
@Deprecated public final void stop()
@Deprecated public final void stop(Throwable throwable)
UnsupportedOperationException
.NullPointerException
- if throwable()
is
null
@Deprecated public final void suspend()
UnsupportedOperationException
.resume()
public String toString()
public static void yield()
public static boolean holdsLock(Object object)
object
- the object to test for the monitor lockpublic void unpark()
See LockSupport
for more
in-depth information of the behavior of this method.
public void parkFor(long nanos)
See LockSupport
for more
in-depth information of the behavior of this method.
This method must only be called when this
is the current
thread.
nanos
- number of nanoseconds to park for or 0
to park indefinitelyIllegalArgumentException
- thrown if nanos < 0
public void parkUntil(long time)
System.currentTimeMillis()
reaches the specified
value, if no other thread unparks it first. If the thread has
been "preemptively unparked," this method cancels that
unparking and returns immediately. This method may also return
spuriously (that is, without the thread being told to unpark
and without the indicated amount of time elapsing).
See LockSupport
for more
in-depth information of the behavior of this method.
This method must only be called when this
is the
current thread.
time
- the time after which the thread should be unparked,
in absolute milliseconds-since-the-epoch