- java.lang.Object
-
- java.lang.Thread
-
- All Implemented Interfaces:
Runnable
- Direct Known Subclasses:
ForkJoinWorkerThread
public class Thread extends Object implements Runnable
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:
Object
,ThreadGroup
-
-
Nested Class Summary
Nested Classes Modifier and Type Class Description static class
Thread.State
The possible Thread states.static interface
Thread.UncaughtExceptionHandler
A handler which is invoked when an uncaught exception occurs in a Thread.
-
Field Summary
Fields Modifier and Type Field Description static int
MAX_PRIORITY
The maximum priority value for a Thread.static int
MIN_PRIORITY
The minimum priority value for a Thread.static int
NORM_PRIORITY
The default priority value for a Thread.
-
Constructor Summary
Constructors Constructor 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 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
All Methods Static Methods Instance Methods Concrete Methods Deprecated Methods Modifier and Type Method Description static int
activeCount()
Returns how many threads are active in theThreadGroup
which the current thread belongs to.void
checkAccess()
This method is used for operations that require approval from a SecurityManager.int
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.static Thread
currentThread()
Answers the instance of Thread that corresponds to the running Thread which calls this method.static void
dumpStack()
Prints a text representation of the 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 arraythreads
passed as parameter.static Map<Thread,StackTraceElement[]>
getAllStackTraces()
Returns a Map containing Thread keys, and values which are arrays of StackTraceElement.ClassLoader
getContextClassLoader()
Returns the context ClassLoader for the receiver.static Thread.UncaughtExceptionHandler
getDefaultUncaughtExceptionHandler()
Return the default UncaughtExceptionHandler used for new Threads.long
getId()
Return a unique id for this Thread.String
getName()
Answers the name of the receiver.int
getPriority()
Answers the priority of the receiver.StackTraceElement[]
getStackTrace()
Returns an array of StackTraceElement, where each element of the array represents a frame on the Java stack.Thread.State
getState()
Returns the current Thread state.ThreadGroup
getThreadGroup()
Answers the ThreadGroup to which the receiver belongsThread.UncaughtExceptionHandler
getUncaughtExceptionHandler()
Return the UncaughtExceptionHandler for this Thread.static boolean
holdsLock(Object object)
Returns whether the current thread has a monitor lock on the specified object.void
interrupt()
Posts an interrupt request to the receiverstatic boolean
interrupted()
Answers aboolean
indicating whether the current Thread (currentThread()
) has a pending interrupt request (true
) or not (false
).boolean
isAlive()
Answerstrue
if the receiver has already been started and still runs code (hasn't died yet).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
isInterrupted()
Answers aboolean
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 timeoutInMilliseconds)
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 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
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.void
resume()
Deprecated.Used with deprecated method Thread.suspend().void
run()
Calls therun()
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)
Set the UncaughtExceptionHandler used for new Threads.void
setName(String threadName)
Sets the name of the receiver.void
setPriority(int requestedPriority)
Sets the priority of the receiver.void
setUncaughtExceptionHandler(Thread.UncaughtExceptionHandler handler)
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.void
stop()
Deprecated.void
suspend()
Deprecated.May cause deadlocks.String
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 Detail
-
MAX_PRIORITY
public static final int MAX_PRIORITY
The maximum priority value for a Thread.- See Also:
- Constant Field Values
-
MIN_PRIORITY
public static final int MIN_PRIORITY
The minimum priority value for a Thread.- See Also:
- Constant Field Values
-
NORM_PRIORITY
public static final int NORM_PRIORITY
The default priority value for a Thread.- See Also:
- Constant Field Values
-
-
Constructor Detail
-
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:
ThreadGroup
-
Thread
public Thread(Runnable runnable)
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:
ThreadGroup
,Runnable
-
Thread
public Thread(Runnable runnable, String threadName)
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:
ThreadGroup
,Runnable
-
Thread
public Thread(String threadName)
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:
ThreadGroup
,Runnable
-
Thread
public Thread(ThreadGroup group, Runnable runnable)
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:
ThreadGroup
,Runnable
,SecurityException
,SecurityManager
-
Thread
public 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.- 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:
ThreadGroup
,Runnable
,SecurityException
,SecurityManager
-
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
public 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.- 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:
ThreadGroup
,Runnable
,SecurityException
,SecurityManager
-
Thread
public Thread(ThreadGroup group, String threadName)
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:
ThreadGroup
,SecurityException
,SecurityManager
-
-
Method Detail
-
activeCount
public static int activeCount()
Returns how many threads are active in theThreadGroup
which the current thread belongs to.- Returns:
- Number of Threads
-
checkAccess
public final void checkAccess()
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:
SecurityException
,SecurityManager
-
countStackFrames
@Deprecated(forRemoval=true, since="1.2") public int 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
-
currentThread
public static Thread 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
public static int enumerate(Thread[] threads)
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:
SecurityException
,SecurityManager
-
getContextClassLoader
public ClassLoader getContextClassLoader()
Returns the context ClassLoader for the receiver.- Returns:
- ClassLoader The context ClassLoader
- See Also:
ClassLoader
,getContextClassLoader()
-
getName
public final String 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:
setPriority(int)
-
getThreadGroup
public final ThreadGroup 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- Throws:
SecurityException
- ifgroup.checkAccess()
fails with a SecurityException- See Also:
SecurityException
,SecurityManager
,interrupted()
,isInterrupted()
-
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:
currentThread()
,interrupt()
,isInterrupted()
-
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:
start()
-
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:
setDaemon(boolean)
-
isInterrupted
public boolean isInterrupted()
Answers aboolean
indicating whether the receiver has a pending interrupt request (true
) or not (false
)- Returns:
- a
boolean
- See Also:
interrupt()
,interrupted()
-
join
public final void join() throws InterruptedException
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:
Object.notifyAll()
,ThreadDeath
-
join
public final void join(long timeoutInMilliseconds) throws InterruptedException
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:
Object.notifyAll()
,ThreadDeath
-
join
public final void join(long timeoutInMilliseconds, int nanos) throws InterruptedException
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:
Object.notifyAll()
,ThreadDeath
-
resume
@Deprecated(forRemoval=false, since="1.2") public final void resume()
Deprecated.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:
suspend()
-
run
public void run()
Calls therun()
method of the Runnable object the receiver holds. If no Runnable is set, does nothing.
-
setContextClassLoader
public void setContextClassLoader(ClassLoader cl)
Set the context ClassLoader for the receiver.- Parameters:
cl
- The context ClassLoader- See Also:
ClassLoader
,getContextClassLoader()
-
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
public final void setName(String threadName)
Sets the name of the receiver.- Parameters:
threadName
- new name for the Thread- Throws:
SecurityException
- ifcheckAccess()
fails with a SecurityException- See Also:
getName()
-
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:
getPriority()
-
sleep
public static void sleep(long time) throws InterruptedException
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:
interrupt()
-
sleep
public static void sleep(long time, int nanos) throws InterruptedException
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:
interrupt()
-
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:
run()
-
stop
@Deprecated(forRemoval=false, since="1.2") public final void 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(forRemoval=false, since="1.2") public final void suspend()
Deprecated.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:
resume()
-
toString
public String 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
public static boolean holdsLock(Object object)
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
public StackTraceElement[] 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:
StackTraceElement
-
getAllStackTraces
public static Map<Thread,StackTraceElement[]> 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:
getStackTrace()
-
getId
public long getId()
Return a unique id for this Thread.- Returns:
- a positive unique id for this Thread.
-
getUncaughtExceptionHandler
public Thread.UncaughtExceptionHandler getUncaughtExceptionHandler()
Return the UncaughtExceptionHandler for this Thread.- Returns:
- the UncaughtExceptionHandler for this Thread
- See Also:
Thread.UncaughtExceptionHandler
-
setUncaughtExceptionHandler
public void setUncaughtExceptionHandler(Thread.UncaughtExceptionHandler handler)
Set the UncaughtExceptionHandler for this Thread.- Parameters:
handler
- the UncaughtExceptionHandler to set- See Also:
Thread.UncaughtExceptionHandler
-
getDefaultUncaughtExceptionHandler
public static Thread.UncaughtExceptionHandler getDefaultUncaughtExceptionHandler()
Return the default UncaughtExceptionHandler used for new Threads.- Returns:
- the default UncaughtExceptionHandler for new Threads
- See Also:
Thread.UncaughtExceptionHandler
-
setDefaultUncaughtExceptionHandler
public static void setDefaultUncaughtExceptionHandler(Thread.UncaughtExceptionHandler handler)
Set the UncaughtExceptionHandler used for new Threads.- Parameters:
handler
- the UncaughtExceptionHandler to set- See Also:
Thread.UncaughtExceptionHandler
-
getState
public Thread.State getState()
Returns the current Thread state.- Returns:
- the current Thread state constant.
- See Also:
Thread.State
-
-