Class Thread
- All Implemented Interfaces:
Runnable
- Direct Known Subclasses:
DeleteOnExit,ForkJoinWorkerThread
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 application
has at least one thread running when it is started, the main thread, in the main
ThreadGroup. The runtime keeps its own threads in the system thread
group.
There are two ways to execute code in a new thread.
You can either subclass Thread and overriding its run() method,
or construct a new Thread and pass a Runnable to the constructor.
In either case, the start() method must be called to actually execute
the new Thread.
Each Thread has an integer priority that affect how the thread is
scheduled by the OS. A new thread inherits the priority of its parent.
A thread's priority can be set using the setPriority(int) method.
-
Nested Class Summary
Nested Classes Modifier and Type Class Description static classThread.StateA representation of a thread's state.static interfaceThread.UncaughtExceptionHandlerImplemented by objects that want to handle cases where a thread is being terminated by an uncaught exception. -
Field Summary
Fields Modifier and Type Field Description static intMAX_PRIORITYThe maximum priority value allowed for a thread.static intMIN_PRIORITYThe minimum priority value allowed for a thread.static intNORM_PRIORITYThe normal (default) priority value assigned to threads. -
Constructor Summary
Constructors Constructor Description Thread()Constructs a newThreadwith noRunnableobject and a newly generated name.Thread(Runnable runnable)Constructs a newThreadwith aRunnableobject and a newly generated name.Thread(Runnable runnable, String threadName)Constructs a newThreadwith aRunnableobject and name provided.Thread(String threadName)Constructs a newThreadwith noRunnableobject and the name provided.Thread(ThreadGroup group, Runnable runnable)Constructs a newThreadwith aRunnableobject and a newly generated name.Thread(ThreadGroup group, Runnable runnable, String threadName)Constructs a newThreadwith aRunnableobject, the given name and belonging to theThreadGrouppassed as parameter.Thread(ThreadGroup group, Runnable runnable, String threadName, long stackSize)Constructs a newThreadwith aRunnableobject, the given name and belonging to theThreadGrouppassed as parameter.Thread(ThreadGroup group, String threadName)Constructs a newThreadwith noRunnableobject, the given name and belonging to theThreadGrouppassed as parameter. -
Method Summary
Modifier and Type Method Description static intactiveCount()Returns the number of activeThreads in the runningThread's group and its subgroups.voidcheckAccess()Does nothing.intcountStackFrames()Deprecated.The results of this call were never well defined.static ThreadcurrentThread()Returns the Thread of the caller, that is, the current Thread.voiddestroy()Deprecated.Not implemented.static voiddumpStack()Prints to the standard error stream a text representation of the current stack for this Thread.static intenumerate(Thread[] threads)Copies an array with all Threads which are in the same ThreadGroup as the receiver - and subgroups - into the arraythreadspassed as parameter.static Map<Thread,StackTraceElement[]>getAllStackTraces()Returns a map of all the currently live threads to their stack traces.ClassLoadergetContextClassLoader()Returns the context ClassLoader for this Thread.static Thread.UncaughtExceptionHandlergetDefaultUncaughtExceptionHandler()Returns the default exception handler that's executed when uncaught exception terminates a thread.longgetId()Returns the thread's identifier.StringgetName()Returns the name of the Thread.intgetPriority()Returns the priority of the Thread.StackTraceElement[]getStackTrace()Returns an array ofStackTraceElementrepresenting the current thread's stack.Thread.StategetState()Returns the current state of the Thread.ThreadGroupgetThreadGroup()Returns the ThreadGroup to which this Thread belongs.Thread.UncaughtExceptionHandlergetUncaughtExceptionHandler()Returns the thread's uncaught exception handler.static booleanholdsLock(Object object)Indicates whether the current Thread has a monitor lock on the specified object.voidinterrupt()Posts an interrupt request to thisThread.static booleaninterrupted()Returns abooleanindicating whether the current Thread (currentThread()) has a pending interrupt request (true) or not (false).booleanisAlive()Returnstrueif the receiver has already been started and still runs code (hasn't died yet).booleanisDaemon()Tests whether this is a daemon thread.booleanisInterrupted()Returns abooleanindicating whether the receiver has a pending interrupt request (true) or not (false)voidjoin()Blocks the current Thread (Thread.currentThread()) until the receiver finishes its execution and dies.voidjoin(long millis)Blocks the current Thread (Thread.currentThread()) until the receiver finishes its execution and dies or the specified timeout expires, whatever happens first.voidjoin(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.voidparkFor(long nanos)Parks the current thread for a particular number of nanoseconds, or indefinitely.voidparkUntil(long time)Parks the current thread until the specified system time.voidpopInterruptAction$(Runnable interruptAction)RemovesinterruptActionso it is not invoked upon interruption.voidpushInterruptAction$(Runnable interruptAction)Adds a runnable to be invoked upon interruption.voidresume()Deprecated.Only useful in conjunction with deprecated methodsuspend().voidrun()Calls therun()method of the Runnable object the receiver holds.voidsetContextClassLoader(ClassLoader cl)Set the context ClassLoader for the receiver.voidsetDaemon(boolean isDaemon)Marks this thread as a daemon thread.static voidsetDefaultUncaughtExceptionHandler(Thread.UncaughtExceptionHandler handler)Sets the default uncaught exception handler.voidsetName(String threadName)Sets the name of the Thread.voidsetPriority(int priority)Sets the priority of this thread.voidsetUncaughtExceptionHandler(Thread.UncaughtExceptionHandler handler)Sets the uncaught exception handler.static voidsleep(long time)Causes the thread which sent this message to sleep for the given interval of time (given in milliseconds).static voidsleep(long millis, int nanos)Causes the thread which sent this message to sleep for the given interval of time (given in milliseconds and nanoseconds).voidstart()Starts the new Thread of execution.voidstop()Deprecated.Stopping a thread in this manner is unsafe and can leave your application and the VM in an unpredictable state.voidstop(Throwable throwable)Deprecated.Stopping a thread in this manner is unsafe and can leave your application and the VM in an unpredictable state.voidsuspend()Deprecated.May cause deadlocks.StringtoString()Returns a string containing a concise, human-readable description of the Thread.voidunpark()Unparks this thread.static voidyield()Causes the calling Thread to yield execution time to another Thread that is ready to run.
-
Field Details
-
MAX_PRIORITY
public static final int MAX_PRIORITYThe maximum priority value allowed for a thread.- See Also:
- Constant Field Values
-
MIN_PRIORITY
public static final int MIN_PRIORITYThe minimum priority value allowed for a thread.- See Also:
- Constant Field Values
-
NORM_PRIORITY
public static final int NORM_PRIORITYThe normal (default) priority value assigned to threads.- See Also:
- Constant Field Values
-
-
Constructor Details
-
Thread
public Thread()Constructs a newThreadwith noRunnableobject and a newly generated name. The newThreadwill belong to the sameThreadGroupas theThreadcalling this constructor.- See Also:
ThreadGroup,Runnable
-
Thread
Constructs a newThreadwith aRunnableobject and a newly generated name. The newThreadwill belong to the sameThreadGroupas theThreadcalling this constructor.- Parameters:
runnable- aRunnablewhose methodrunwill be executed by the newThread- See Also:
ThreadGroup,Runnable
-
Thread
Constructs a newThreadwith aRunnableobject and name provided. The newThreadwill belong to the sameThreadGroupas theThreadcalling this constructor.- Parameters:
runnable- aRunnablewhose methodrunwill be executed by the newThreadthreadName- the name for theThreadbeing created- See Also:
ThreadGroup,Runnable
-
Thread
Constructs a newThreadwith noRunnableobject and the name provided. The newThreadwill belong to the sameThreadGroupas theThreadcalling this constructor.- Parameters:
threadName- the name for theThreadbeing created- See Also:
ThreadGroup,Runnable
-
Thread
Constructs a newThreadwith aRunnableobject and a newly generated name. The newThreadwill belong to theThreadGrouppassed as parameter.- Parameters:
group-ThreadGroupto which the newThreadwill belongrunnable- aRunnablewhose methodrunwill be executed by the newThread- Throws:
IllegalThreadStateException- ifgroup.destroy()has already been done- See Also:
ThreadGroup,Runnable
-
Thread
Constructs a newThreadwith aRunnableobject, the given name and belonging to theThreadGrouppassed as parameter.- Parameters:
group- ThreadGroup to which the newThreadwill belongrunnable- aRunnablewhose methodrunwill be executed by the newThreadthreadName- the name for theThreadbeing created- Throws:
IllegalThreadStateException- ifgroup.destroy()has already been done- See Also:
ThreadGroup,Runnable
-
Thread
Constructs a newThreadwith noRunnableobject, the given name and belonging to theThreadGrouppassed as parameter.- Parameters:
group-ThreadGroupto which the newThreadwill belongthreadName- the name for theThreadbeing created- Throws:
IllegalThreadStateException- ifgroup.destroy()has already been done- See Also:
ThreadGroup,Runnable
-
Thread
Constructs a newThreadwith aRunnableobject, the given name and belonging to theThreadGrouppassed as parameter.- Parameters:
group-ThreadGroupto which the newThreadwill belongrunnable- aRunnablewhose methodrunwill be executed by the newThreadthreadName- the name for theThreadbeing createdstackSize- a stack size for the newThread. This has a highly platform-dependent interpretation. It may even be ignored completely.- Throws:
IllegalThreadStateException- ifgroup.destroy()has already been done- See Also:
ThreadGroup,Runnable
-
-
Method Details
-
activeCount
public static int activeCount()Returns the number of activeThreads in the runningThread's group and its subgroups.- Returns:
- the number of
Threads
-
checkAccess
public final void checkAccess()Does nothing. -
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.Returns the number of stack frames in this thread.- Returns:
- Number of stack frames
-
currentThread
Returns the Thread of the caller, that is, the current Thread.- Returns:
- the current Thread.
-
destroy
Deprecated.Not implemented.ThrowsUnsupportedOperationException. -
dumpStack
public static void dumpStack()Prints to the standard error stream a text representation of the current stack for this Thread.- See Also:
Throwable.printStackTrace()
-
enumerate
Copies an array with all Threads which are in the same ThreadGroup as the receiver - and subgroups - into the arraythreadspassed 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
-
getAllStackTraces
Returns a map of all the currently live threads to their stack traces. -
getContextClassLoader
Returns the context ClassLoader for this Thread.- Returns:
- ClassLoader The context ClassLoader
- See Also:
ClassLoader,getContextClassLoader()
-
getDefaultUncaughtExceptionHandler
Returns the default exception handler that's executed when uncaught exception terminates a thread.- Returns:
- an
Thread.UncaughtExceptionHandlerornullif none exists.
-
getId
public long getId()Returns the thread's identifier. The ID is a positivelonggenerated 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.- Returns:
- the thread's ID.
-
getName
Returns the name of the Thread. -
getPriority
public final int getPriority()Returns the priority of the Thread. -
getStackTrace
Returns an array ofStackTraceElementrepresenting the current thread's stack. -
getState
Returns the current state of the Thread. This method is useful for monitoring purposes.- Returns:
- a
Thread.Statevalue.
-
getThreadGroup
Returns the ThreadGroup to which this Thread belongs.- Returns:
- the Thread's ThreadGroup
-
getUncaughtExceptionHandler
Returns the thread's uncaught exception handler. If not explicitly set, then the ThreadGroup's handler is returned. If the thread is terminated, thennullis returned.- Returns:
- an
Thread.UncaughtExceptionHandlerinstance ornull.
-
interrupt
public void interrupt()Posts an interrupt request to thisThread. The behavior depends on the state of thisThread:-
Threads blocked in one ofObject'swait()methods or one ofThread'sjoin()orsleep()methods will be woken up, their interrupt status will be cleared, and they receive anInterruptedException. -
Threads blocked in an I/O operation of anInterruptibleChannelwill have their interrupt status set and receive anClosedByInterruptException. Also, the channel will be closed. -
Threads blocked in aSelectorwill have their interrupt status set and return immediately. They don't receive an exception in this case.
- See Also:
interrupted(),isInterrupted()
-
-
interrupted
public static boolean interrupted()Returns abooleanindicating 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
booleanindicating the interrupt status - See Also:
currentThread(),interrupt(),isInterrupted()
-
isAlive
public final boolean isAlive()Returnstrueif the receiver has already been started and still runs code (hasn't died yet). Returnsfalseeither if the receiver hasn't been started yet or if it has already started and run to completion and died.- Returns:
- a
booleanindicating the liveness of the Thread - See Also:
start()
-
isDaemon
public final boolean isDaemon()Tests whether this is a daemon thread. A daemon thread only runs as long as there are non-daemon threads running. When the last non-daemon thread ends, the runtime will exit. This is not normally relevant to applications with a UI. -
isInterrupted
public boolean isInterrupted()Returns abooleanindicating whether the receiver has a pending interrupt request (true) or not (false)- Returns:
- a
booleanindicating the interrupt status - See Also:
interrupt(),interrupted()
-
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:
Object.notifyAll(),ThreadDeath
-
join
Blocks the current Thread (Thread.currentThread()) until the receiver finishes its execution and dies or the specified timeout expires, whatever happens first.- Parameters:
millis- 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
Blocks the current Thread (Thread.currentThread()) until the receiver finishes its execution and dies or the specified timeout expires, whatever happens first.- Parameters:
millis- 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.Only useful in conjunction with deprecated methodsuspend().ThrowsUnsupportedOperationException. -
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:
getContextClassLoader()
-
setDaemon
public final void setDaemon(boolean isDaemon)Marks this thread as a daemon thread. A daemon thread only runs as long as there are non-daemon threads running. When the last non-daemon thread ends, the runtime will exit. This is not normally relevant to applications with a UI.- Throws:
IllegalThreadStateException- - if this thread has already started.
-
setDefaultUncaughtExceptionHandler
Sets the default uncaught exception handler. This handler is invoked in case any Thread dies due to an unhandled exception.- Parameters:
handler- The handler to set or null.
-
pushInterruptAction$
Adds a runnable to be invoked upon interruption. If this thread has already been interrupted, the runnable will be invoked immediately. The action should be idempotent as it may be invoked multiple times for a single interruption.Each call to this method must be matched with a corresponding call to
popInterruptAction$(java.lang.Runnable). -
popInterruptAction$
RemovesinterruptActionso it is not invoked upon interruption.- Parameters:
interruptAction- the pushed action, used to check that the call stack is correctly nested.
-
setName
Sets the name of the Thread.- Parameters:
threadName- the new name for the Thread- See Also:
getName()
-
setPriority
public final void setPriority(int priority)Sets the priority of this thread. If the requested priority is greater than the parent thread group'sThreadGroup.getMaxPriority(), the group's maximum priority will be used instead.- Throws:
IllegalArgumentException- - if the new priority is greater thanMAX_PRIORITYor less thanMIN_PRIORITY
-
setUncaughtExceptionHandler
Sets the uncaught exception handler. This handler is invoked in case this Thread dies due to an unhandled exception.
- Parameters:
handler- The handler to set ornull.
-
sleep
Causes the thread which sent this message to sleep for the given 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
Causes the thread which sent this message to sleep for the given interval of time (given in milliseconds and nanoseconds). The precision is not guaranteed - the Thread may sleep more or less than requested.- Parameters:
millis- 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()
-
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- - if this thread has already started.- See Also:
run()
-
stop
Deprecated.Stopping a thread in this manner is unsafe and can leave your application and the VM in an unpredictable state.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. -
stop
Deprecated.Stopping a thread in this manner is unsafe and can leave your application and the VM in an unpredictable state.ThrowsUnsupportedOperationException. -
suspend
Deprecated.May cause deadlocks.ThrowsUnsupportedOperationException. -
toString
Returns a string containing a concise, human-readable description of the Thread. It includes the Thread's name, priority, and group name. -
yield
public static void yield()Causes the calling Thread to yield execution time to another Thread that is ready to run. The actual scheduling is implementation-dependent. -
holdsLock
Indicates whether the current Thread has a monitor lock on the specified object.- Parameters:
object- the object to test for the monitor lock- Returns:
- true if the current thread has a monitor lock on the specified object; false otherwise
-
unpark
public void unpark()Unparks this thread. This unblocks the thread it if it was previously parked, or indicates that the thread is "preemptively unparked" if it wasn't already parked. The latter means that the next time the thread is told to park, it will merely clear its latent park bit and carry on without blocking.See
LockSupportfor more in-depth information of the behavior of this method. -
parkFor
public void parkFor(long nanos)Parks the current thread for a particular number of nanoseconds, or indefinitely. If not indefinitely, this method unparks the thread after the given number of nanoseconds 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
LockSupportfor more in-depth information of the behavior of this method.This method must only be called when
thisis the current thread.- Parameters:
nanos- number of nanoseconds to park for or0to park indefinitely- Throws:
IllegalArgumentException- thrown ifnanos < 0
-
parkUntil
public void parkUntil(long time)Parks the current thread until the specified system time. This method attempts to unpark the current thread immediately afterSystem.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
LockSupportfor more in-depth information of the behavior of this method.This method must only be called when
thisis the current thread.- Parameters:
time- the time after which the thread should be unparked, in absolute milliseconds-since-the-epoch
-