java.lang.Object
java.lang.Thread
- All Implemented Interfaces:
Runnable
- Direct Known Subclasses:
ForkJoinWorkerThread
A Thread is a unit of concurrent execution in Java. It has its own call stack
for methods being called and their parameters. Threads 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 Threads to cooperate.
When a Java program starts executing there is an implicit Thread (called "main")
which is automatically created by the VM. This Thread belongs to a ThreadGroup
(also called "main") which is automatically created by the bootstrap sequence by
the VM as well.
- See Also:
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionstatic enum
The possible Thread states.static interface
A handler which is invoked when an uncaught exception occurs in a Thread. -
Field Summary
FieldsModifier and TypeFieldDescriptionstatic final int
The maximum priority value for a Thread.static final int
The minimum priority value for a Thread.static final int
The default priority value for a Thread. -
Constructor Summary
ConstructorsConstructorDescriptionThread()
Constructs a new Thread with no runnable object and a newly generated name.Constructs a new Thread with a runnable object and a newly generated name.Constructs a new Thread with a runnable object and name provided.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 stack) 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 stack, boolean inheritThreadLocals) Constructs a new Thread with a runnable object, the given name, the thread stack size, the flag to inherit initial values for inheritable thread-local variables 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. -
Method Summary
Modifier and TypeMethodDescriptionstatic int
Returns how many threads are active in theThreadGroup
which the current thread belongs to.final void
Deprecated, for removal: This API element is subject to removal in a future version.int
Deprecated, for removal: This API element is subject to removal in a future version.The semantics of this method are poorly defined and it uses the deprecated suspend() method.static Thread
Answers the instance of Thread that corresponds to the running Thread which calls this method.static void
Prints a text representation of the stack for this Thread.static int
Copies an array with all Threads which are in the same ThreadGroup as the receiver - and subgroups - into the arraythreads
passed as parameter.static Map<Thread,
StackTraceElement[]> Returns a Map containing Thread keys, and values which are arrays of StackTraceElement.Returns the context ClassLoader for the receiver.Return the default UncaughtExceptionHandler used for new Threads.long
getId()
Return a unique id for this Thread.final String
getName()
Answers the name of the receiver.final int
Answers the priority of the receiver.Returns an array of StackTraceElement, where each element of the array represents a frame on the Java stack.getState()
Returns the current Thread state.final ThreadGroup
Answers the ThreadGroup to which the receiver belongsReturn the UncaughtExceptionHandler for this Thread.static boolean
Returns whether the current thread has a monitor lock on the specified object.void
Posts an interrupt request to the receiver From Java 14, the interrupt state for threads that are not alive is tracked.static boolean
Answers aboolean
indicating whether the current Thread (currentThread()
) has a pending interrupt request (true
) or not (false
).final boolean
isAlive()
Answerstrue
if the receiver has already been started and still runs code (hasn't died yet).final boolean
isDaemon()
Answers aboolean
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
Answers aboolean
indicating whether the receiver has a pending interrupt request (true
) or not (false
)final void
join()
Blocks the current Thread (Thread.currentThread()
) until the receiver finishes its execution and dies.final void
join
(long timeoutInMilliseconds) Blocks the current Thread (Thread.currentThread()
) until the receiver finishes its execution and dies or the specified timeout expires, whatever happens first.final void
join
(long timeoutInMilliseconds, int nanos) Blocks the current Thread (Thread.currentThread()
) until the receiver finishes its execution and dies or the specified timeout expires, whatever happens first.static void
Hints to the run-time that a spin loop is being performed which helps the thread in the spin loop not to use as much power.final void
resume()
Deprecated, for removal: This API element is subject to removal in a future version.Used with deprecated method Thread.suspend().void
run()
Calls therun()
method of the Runnable object the receiver holds.void
Set the context ClassLoader for the receiver.final void
setDaemon
(boolean isDaemon) Set if the receiver is a daemon Thread or not.static void
Set the UncaughtExceptionHandler used for new Threads.final void
Sets the name of the receiver.final void
setPriority
(int requestedPriority) Sets the priority of the receiver.void
Set the UncaughtExceptionHandler for this Thread.static void
sleep
(long time) Causes the thread which sent this message to sleep an interval of time (given in milliseconds).static void
sleep
(long time, int nanos) Causes the thread which sent this message to sleep an interval of time (given in milliseconds).void
start()
Starts the new Thread of execution.final void
stop()
Deprecated.final void
suspend()
Deprecated, for removal: This API element is subject to removal in a future version.May cause deadlocks.toString()
Answers a string containing a concise, human-readable description of the receiver.static void
yield()
Causes the thread which sent this message to yield execution to another Thread that is ready to run.
-
Field Details
-
MAX_PRIORITY
public static final int MAX_PRIORITYThe maximum priority value for a Thread.- See Also:
-
MIN_PRIORITY
public static final int MIN_PRIORITYThe minimum priority value for a Thread.- See Also:
-
NORM_PRIORITY
public static final int NORM_PRIORITYThe default priority value for a Thread.- See Also:
-
-
Constructor Details
-
Thread
public Thread()Constructs a new 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.- See Also:
-
Thread
Constructs a new 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.- Parameters:
runnable
- a java.lang.Runnable whose methodrun
will be executed by the new Thread- See Also:
-
Thread
Constructs a new Thread with a runnable object and name provided. The new Thread will belong to the same ThreadGroup as the Thread calling this constructor.- Parameters:
runnable
- a java.lang.Runnable whose methodrun
will be executed by the new ThreadthreadName
- Name for the Thread being created- See Also:
-
Thread
Constructs a new Thread with no runnable object and the name provided. The new Thread will belong to the same ThreadGroup as the Thread calling this constructor.- Parameters:
threadName
- Name for the Thread being created- See Also:
-
Thread
Constructs a new Thread with a runnable object and a newly generated name. The new Thread will belong to the ThreadGroup passed as parameter.- Parameters:
group
- ThreadGroup to which the new Thread will belongrunnable
- a java.lang.Runnable whose methodrun
will be executed by the new Thread- Throws:
SecurityException
- ifgroup.checkAccess()
fails with a SecurityExceptionIllegalThreadStateException
- ifgroup.destroy()
has already been done- See Also:
-
Thread
Constructs a new Thread with a runnable object, the given name and belonging to the ThreadGroup passed as parameter.- Parameters:
group
- ThreadGroup to which the new Thread will belongrunnable
- a java.lang.Runnable whose methodrun
will be executed by the new ThreadthreadName
- Name for the Thread being createdstack
- Platform dependent stack size- Throws:
SecurityException
- ifgroup.checkAccess()
fails with a SecurityExceptionIllegalThreadStateException
- ifgroup.destroy()
has already been done- Since:
- 1.4
- See Also:
-
Thread
public Thread(ThreadGroup group, Runnable runnable, String threadName, long stack, boolean inheritThreadLocals) Constructs a new Thread with a runnable object, the given name, the thread stack size, the flag to inherit initial values for inheritable thread-local variables and belonging to the ThreadGroup passed as parameter.- Parameters:
group
- ThreadGroup to which the new Thread will belongrunnable
- A java.lang.Runnable whose methodrun
will be executed by the new ThreadthreadName
- Name for the Thread being createdstack
- Platform dependent stack sizeinheritThreadLocals
- A boolean indicating whether to inherit initial values for inheritable thread-local variables.- Throws:
SecurityException
- ifgroup.checkAccess()
fails with a SecurityExceptionIllegalThreadStateException
- ifgroup.destroy()
has already been done
-
Thread
Constructs a new Thread with a runnable object, the given name and belonging to the ThreadGroup passed as parameter.- Parameters:
group
- ThreadGroup to which the new Thread will belongrunnable
- a java.lang.Runnable whose methodrun
will be executed by the new ThreadthreadName
- Name for the Thread being created- Throws:
SecurityException
- ifgroup.checkAccess()
fails with a SecurityExceptionIllegalThreadStateException
- ifgroup.destroy()
has already been done- See Also:
-
Thread
Constructs a new Thread with no runnable object, the given name and belonging to the ThreadGroup passed as parameter.- Parameters:
group
- ThreadGroup to which the new Thread will belongthreadName
- Name for the Thread being created- Throws:
SecurityException
- ifgroup.checkAccess()
fails with a SecurityExceptionIllegalThreadStateException
- ifgroup.destroy()
has already been done- See Also:
-
-
Method Details
-
activeCount
public static int activeCount()Returns how many threads are active in theThreadGroup
which the current thread belongs to.- Returns:
- Number of Threads
-
checkAccess
Deprecated, for removal: This API element is subject to removal in a future version.This method is used for operations that require approval from a SecurityManager. If there's none installed, this method is a no-op. If there's a SecurityManager installed ,checkAccess(Ljava.lang.Thread;)
is called for that SecurityManager.- See Also:
-
countStackFrames
Deprecated, for removal: This API element is subject to removal in a future version.The semantics of this method are poorly defined and it uses the deprecated suspend() method.Returns the number of stack frames in this thread.- Returns:
- Number of stack frames
- Throws:
UnsupportedOperationException
-
currentThread
Answers the instance of Thread that corresponds to the running Thread which calls this method.- Returns:
- a java.lang.Thread corresponding to the code that called
currentThread()
-
dumpStack
public static void dumpStack()Prints a text representation of the stack for this Thread. -
enumerate
Copies an array with all Threads which are in the same ThreadGroup as the receiver - and subgroups - into the arraythreads
passed as parameter. If the array passed as parameter is too small no exception is thrown - the extra elements are simply not copied.- Parameters:
threads
- array into which the Threads will be copied- Returns:
- How many Threads were copied over
- Throws:
SecurityException
- if the installed SecurityManager failscheckAccess(Ljava.lang.Thread;)
- See Also:
-
getContextClassLoader
Returns the context ClassLoader for the receiver.- Returns:
- ClassLoader The context ClassLoader
- See Also:
-
getName
Answers the name of the receiver.- Returns:
- the receiver's name (a java.lang.String)
-
getPriority
public final int getPriority()Answers the priority of the receiver.- Returns:
- the receiver's priority (an
int
) - See Also:
-
getThreadGroup
Answers the ThreadGroup to which the receiver belongs- Returns:
- the receiver's ThreadGroup
-
interrupt
public void interrupt()Posts an interrupt request to the receiver From Java 14, the interrupt state for threads that are not alive is tracked.- Throws:
SecurityException
- ifgroup.checkAccess()
fails with a SecurityException- See Also:
-
interrupted
public static boolean interrupted()Answers aboolean
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.- Returns:
- a
boolean
- See Also:
-
isAlive
public final boolean isAlive()Answerstrue
if the receiver has already been started and still runs code (hasn't died yet). Answersfalse
either if the receiver hasn't been started yet or if it has already started and run to completion and died.- Returns:
- a
boolean
- See Also:
-
isDaemon
public final boolean isDaemon()Answers aboolean
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.- Returns:
- a
boolean
- See Also:
-
isInterrupted
public boolean isInterrupted()Answers aboolean
indicating whether the receiver has a pending interrupt request (true
) or not (false
)- Returns:
- a
boolean
- See Also:
-
join
Blocks the current Thread (Thread.currentThread()
) until the receiver finishes its execution and dies.- Throws:
InterruptedException
- ifinterrupt()
was called for the receiver while it was in thejoin()
call- See Also:
-
join
Blocks the current Thread (Thread.currentThread()
) until the receiver finishes its execution and dies or the specified timeout expires, whatever happens first.- Parameters:
timeoutInMilliseconds
- The maximum time to wait (in milliseconds).- Throws:
InterruptedException
- ifinterrupt()
was called for the receiver while it was in thejoin()
call- See Also:
-
join
Blocks the current Thread (Thread.currentThread()
) until the receiver finishes its execution and dies or the specified timeout expires, whatever happens first.- Parameters:
timeoutInMilliseconds
- The maximum time to wait (in milliseconds).nanos
- Extra nanosecond precision- Throws:
InterruptedException
- ifinterrupt()
was called for the receiver while it was in thejoin()
call- See Also:
-
resume
Deprecated, for removal: This API element is subject to removal in a future version.Used with deprecated method Thread.suspend().This is a no-op if the receiver was never suspended, or suspended and already resumed. If the receiver is suspended, however, makes it resume to the point where it was when it was suspended.- Throws:
SecurityException
- ifcheckAccess()
fails with a SecurityException- See Also:
-
run
public void run()Calls therun()
method of the Runnable object the receiver holds. If no Runnable is set, does nothing. -
setContextClassLoader
Set the context ClassLoader for the receiver.- Parameters:
cl
- The context ClassLoader- See Also:
-
setDaemon
public final void setDaemon(boolean isDaemon) Set if the receiver is a daemon Thread or not. This can only be done before the Thread starts running.- Parameters:
isDaemon
- A boolean indicating if the Thread should be daemon or not- Throws:
SecurityException
- ifcheckAccess()
fails with a SecurityException- See Also:
-
isDaemon
-
setName
Sets the name of the receiver.- Parameters:
threadName
- new name for the Thread- Throws:
SecurityException
- ifcheckAccess()
fails with a SecurityException- See Also:
-
setPriority
public final void setPriority(int requestedPriority) Sets the priority of the receiver. Note that the final priority set may be less than the requested value, as it is bounded by the maxPriority() of the receiver's ThreadGroup.- Parameters:
requestedPriority
- new priority for the Thread- Throws:
SecurityException
- ifcheckAccess()
fails with a SecurityExceptionIllegalArgumentException
- if the new priority is greater than Thread.MAX_PRIORITY or less than Thread.MIN_PRIORITY- See Also:
-
sleep
Causes the thread which sent this message to sleep an interval of time (given in milliseconds). The precision is not guaranteed - the Thread may sleep more or less than requested.- Parameters:
time
- The time to sleep in milliseconds.- Throws:
InterruptedException
- ifinterrupt()
was called for this Thread while it was sleeping- See Also:
-
sleep
Causes the thread which sent this message to sleep an interval of time (given in milliseconds). The precision is not guaranteed - the Thread may sleep more or less than requested.- Parameters:
time
- The time to sleep in milliseconds.nanos
- Extra nanosecond precision- Throws:
InterruptedException
- ifinterrupt()
was called for this Thread while it was sleeping- See Also:
-
onSpinWait
public static void onSpinWait()Hints to the run-time that a spin loop is being performed which helps the thread in the spin loop not to use as much power. -
start
public void start()Starts the new Thread of execution. Therun()
method of the receiver will be called by the receiver Thread itself (and not the Thread callingstart()
).- Throws:
IllegalThreadStateException
- Unspecified in the Java language specification- See Also:
-
stop
Deprecated.Requests the receiver Thread to stop and throw ThreadDeath. The Thread is resumed if it was suspended and awakened if it was sleeping, so that it can proceed to throw ThreadDeath.- Throws:
SecurityException
- ifcheckAccess()
fails with a SecurityException
-
suspend
Deprecated, for removal: This API element is subject to removal in a future version.May cause deadlocks.This is a no-op if the receiver is suspended. If the receiverisAlive()
however, suspended it untilresume()
is sent to it. Suspend requests are not queued, which means that N requests are equivalent to just one - only one resume request is needed in this case.- Throws:
SecurityException
- ifcheckAccess()
fails with a SecurityException- See Also:
-
toString
Answers a string containing a concise, human-readable description of the receiver. -
yield
public static void yield()Causes the thread which sent this message to yield execution to another Thread that is ready to run. The actual scheduling is implementation-dependent. -
holdsLock
Returns whether the current thread has a monitor lock on the specified object.- Parameters:
object
- the object to test for the monitor lock- Returns:
- true when the current thread has a monitor lock on the specified object
- Since:
- 1.4
-
getStackTrace
Returns an array of StackTraceElement, where each element of the array represents a frame on the Java stack.- Returns:
- an array of StackTraceElement
- Throws:
SecurityException
- if the RuntimePermission "getStackTrace" is not allowed- See Also:
-
getAllStackTraces
Returns a Map containing Thread keys, and values which are arrays of StackTraceElement. The Map contains all Threads which were alive at the time this method was called.- Returns:
- an array of StackTraceElement
- Throws:
SecurityException
- if the RuntimePermission "getStackTrace" is not allowed, or the RuntimePermission "modifyThreadGroup" is not allowed- See Also:
-
getId
public long getId()Return a unique id for this Thread.- Returns:
- a positive unique id for this Thread.
-
getUncaughtExceptionHandler
Return the UncaughtExceptionHandler for this Thread.- Returns:
- the UncaughtExceptionHandler for this Thread
- See Also:
-
setUncaughtExceptionHandler
Set the UncaughtExceptionHandler for this Thread.- Parameters:
handler
- the UncaughtExceptionHandler to set- See Also:
-
getDefaultUncaughtExceptionHandler
Return the default UncaughtExceptionHandler used for new Threads.- Returns:
- the default UncaughtExceptionHandler for new Threads
- See Also:
-
setDefaultUncaughtExceptionHandler
Set the UncaughtExceptionHandler used for new Threads.- Parameters:
handler
- the UncaughtExceptionHandler to set- See Also:
-
getState
Returns the current Thread state.- Returns:
- the current Thread state constant.
- See Also:
-