Module java.base
Package java.lang

Class Thread

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:
  • Nested Class Summary

    Nested Classes
    Modifier and Type
    Class
    Description
    static enum 
    The possible Thread states.
    static interface 
    A handler which is invoked when an uncaught exception occurs in a Thread.
  • Field Summary

    Fields
    Modifier and Type
    Field
    Description
    static 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

    Constructors
    Constructor
    Description
    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

    Modifier and Type
    Method
    Description
    static int
    Returns how many threads are active in the ThreadGroup 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
    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.
    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
    Return a unique id for this Thread.
    final String
    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.
    Returns the current Thread state.
    Answers the ThreadGroup to which the receiver belongs
    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
    Posts an interrupt request to the receiver From Java 14, the interrupt state for threads that are not alive is tracked.
    static boolean
    Answers a boolean indicating whether the current Thread (currentThread()) has a pending interrupt request (true) or not (false).
    final boolean
    Answers true if the receiver has already been started and still runs code (hasn't died yet).
    final boolean
    Answers 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
    Answers a boolean indicating whether the receiver has a pending interrupt request (true) or not (false)
    final void
    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
    Deprecated, for removal: This API element is subject to removal in a future version.
    Used with deprecated method Thread.suspend().
    void
    run()
    Calls the run() 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
    setName(String threadName)
    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
    Starts the new Thread of execution.
    final void
    Deprecated. 
    final void
    Deprecated, for removal: This API element is subject to removal in a future version.
    May cause deadlocks.
    Answers a string containing a concise, human-readable description of the receiver.
    static void
    Causes the thread which sent this message to yield execution to another Thread that is ready to run.

    Methods declared in class java.lang.Object

    clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
  • Field Details

    • MAX_PRIORITY

      public static final int MAX_PRIORITY
      The maximum priority value for a Thread.
      See Also:
    • MIN_PRIORITY

      public static final int MIN_PRIORITY
      The minimum priority value for a Thread.
      See Also:
    • NORM_PRIORITY

      public static final int NORM_PRIORITY
      The 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

      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 method run will be executed by the new Thread
      See Also:
    • 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 method run will be executed by the new Thread
      threadName - Name for the Thread being created
      See Also:
    • 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:
    • 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 belong
      runnable - a java.lang.Runnable whose method run will be executed by the new Thread
      Throws:
      SecurityException - if group.checkAccess() fails with a SecurityException
      IllegalThreadStateException - if group.destroy() has already been done
      See Also:
    • 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 belong
      runnable - a java.lang.Runnable whose method run will be executed by the new Thread
      threadName - Name for the Thread being created
      stack - Platform dependent stack size
      Throws:
      SecurityException - if group.checkAccess() fails with a SecurityException
      IllegalThreadStateException - if group.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 belong
      runnable - A java.lang.Runnable whose method run will be executed by the new Thread
      threadName - Name for the Thread being created
      stack - Platform dependent stack size
      inheritThreadLocals - A boolean indicating whether to inherit initial values for inheritable thread-local variables.
      Throws:
      SecurityException - if group.checkAccess() fails with a SecurityException
      IllegalThreadStateException - if group.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 belong
      runnable - a java.lang.Runnable whose method run will be executed by the new Thread
      threadName - Name for the Thread being created
      Throws:
      SecurityException - if group.checkAccess() fails with a SecurityException
      IllegalThreadStateException - if group.destroy() has already been done
      See Also:
    • 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 belong
      threadName - Name for the Thread being created
      Throws:
      SecurityException - if group.checkAccess() fails with a SecurityException
      IllegalThreadStateException - if group.destroy() has already been done
      See Also:
  • Method Details

    • activeCount

      public static int activeCount()
      Returns how many threads are active in the ThreadGroup which the current thread belongs to.
      Returns:
      Number of Threads
    • checkAccess

      @Deprecated(since="17", forRemoval=true) public final void 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(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
      Throws:
      UnsupportedOperationException
    • 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 array threads 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 fails checkAccess(Ljava.lang.Thread;)
      See Also:
    • getContextClassLoader

      public ClassLoader getContextClassLoader()
      Returns the context ClassLoader for the receiver.
      Returns:
      ClassLoader The context ClassLoader
      See Also:
    • 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:
    • 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 From Java 14, the interrupt state for threads that are not alive is tracked.
      Throws:
      SecurityException - if group.checkAccess() fails with a SecurityException
      See Also:
    • interrupted

      public static boolean interrupted()
      Answers a 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.
      Returns:
      a boolean
      See Also:
    • isAlive

      public final boolean isAlive()
      Answers true if the receiver has already been started and still runs code (hasn't died yet). Answers false 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 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. 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 a boolean indicating whether the receiver has a pending interrupt request (true) or not (false)
      Returns:
      a boolean
      See Also:
    • join

      public final void join() throws InterruptedException
      Blocks the current Thread (Thread.currentThread()) until the receiver finishes its execution and dies.
      Throws:
      InterruptedException - if interrupt() was called for the receiver while it was in the join() call
      See Also:
    • 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 - if interrupt() was called for the receiver while it was in the join() call
      See Also:
    • 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 - if interrupt() was called for the receiver while it was in the join() call
      See Also:
    • resume

      @Deprecated(forRemoval=true, since="1.2") public final void 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 - if checkAccess() fails with a SecurityException
      See Also:
    • run

      public void run()
      Calls the run() method of the Runnable object the receiver holds. If no Runnable is set, does nothing.
      Specified by:
      run in interface Runnable
      See Also:
    • setContextClassLoader

      public void setContextClassLoader(ClassLoader cl)
      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 - if checkAccess() 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 - if checkAccess() 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 - if checkAccess() fails with a SecurityException
      IllegalArgumentException - if the new priority is greater than Thread.MAX_PRIORITY or less than Thread.MIN_PRIORITY
      See Also:
    • 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 - if interrupt() was called for this Thread while it was sleeping
      See Also:
    • 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 - if interrupt() 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. The run() method of the receiver will be called by the receiver Thread itself (and not the Thread calling start()).
      Throws:
      IllegalThreadStateException - Unspecified in the Java language specification
      See Also:
    • 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 - if checkAccess() fails with a SecurityException
    • suspend

      @Deprecated(forRemoval=true, since="1.2") public final void 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 receiver isAlive() however, suspended it until resume() 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 - if checkAccess() fails with a SecurityException
      See Also:
    • toString

      public String toString()
      Answers a string containing a concise, human-readable description of the receiver.
      Overrides:
      toString in class Object
      Returns:
      a printable representation for 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:
    • 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:
    • 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:
    • setUncaughtExceptionHandler

      public void setUncaughtExceptionHandler(Thread.UncaughtExceptionHandler handler)
      Set the UncaughtExceptionHandler for this Thread.
      Parameters:
      handler - the UncaughtExceptionHandler to set
      See Also:
    • getDefaultUncaughtExceptionHandler

      public static Thread.UncaughtExceptionHandler getDefaultUncaughtExceptionHandler()
      Return the default UncaughtExceptionHandler used for new Threads.
      Returns:
      the default UncaughtExceptionHandler for new Threads
      See Also:
    • setDefaultUncaughtExceptionHandler

      public static void setDefaultUncaughtExceptionHandler(Thread.UncaughtExceptionHandler handler)
      Set the UncaughtExceptionHandler used for new Threads.
      Parameters:
      handler - the UncaughtExceptionHandler to set
      See Also:
    • getState

      public Thread.State getState()
      Returns the current Thread state.
      Returns:
      the current Thread state constant.
      See Also: