Thread defines constructors and a Builder to create threads.
Starting a thread schedules it to execute its run
method. The newly started thread executes concurrently with the thread that caused
it to start.
A thread terminates if either its run method completes normally,
or if its run method completes abruptly and the appropriate uncaught exception handler completes normally or
abruptly. With no code left to run, the thread has completed execution. The isAlive method can be used to test if a started thread has terminated.
The join method can be used to wait for a thread to terminate.
Threads have a unique identifier and a name. The identifier is generated when a Thread is created
and cannot be changed. The thread name can be specified when creating a thread
or can be changed at a later time.
Threads support ThreadLocal variables. These are variables that are
local to a thread, meaning a thread can have a copy of a variable that is set to
a value that is independent of the value set by other threads. Thread also
supports InheritableThreadLocal variables that are thread local variables
that are inherited at thread creation time from the parent Thread.
Thread supports a special inheritable thread local for the thread
context-class-loader.
Thread supports the creation of platform threads that are
typically mapped 1:1 to kernel threads scheduled by the operating system.
Platform threads will usually have a large stack and other resources that are
maintained by the operating system. Platforms threads are suitable for executing
all types of tasks but may be a limited resource.
Platform threads get an automatically generated thread name by default.
Platform threads are designated daemon or non-daemon threads.
When the Java virtual machine starts up, there is usually one non-daemon
thread (the thread that typically calls the application's main method).
The shutdown sequence begins when all started
non-daemon threads have terminated. Unstarted non-daemon threads do not prevent
the shutdown sequence from beginning.
In addition to the daemon status, platform threads have a thread priority and are members of a thread group.
Thread also supports the creation of virtual threads.
Virtual threads are typically user-mode threads scheduled by the Java
runtime rather than the operating system. Virtual threads will typically require
few resources and a single Java virtual machine may support millions of virtual
threads. Virtual threads are suitable for executing tasks that spend most of
the time blocked, often waiting for I/O operations to complete. Virtual threads
are not intended for long running CPU intensive operations.
Virtual threads typically employ a small set of platform threads used as
carrier threads. Locking and I/O operations are examples of operations
where a carrier thread may be re-scheduled from one virtual thread to another.
Code executing in a virtual thread is not aware of the underlying carrier thread.
The Thread#currentThread() method, used to obtain a reference
to the current thread, will always return the Thread object
for the virtual thread.
Virtual threads do not have a thread name by default. The getName method returns the empty string if a thread name is not set.
Virtual threads are daemon threads and so do not prevent the shutdown sequence from beginning. Virtual threads have a fixed thread priority that cannot be changed.
Thread defines public constructors for creating platform threads and
the start method to schedule threads to execute. Thread
may be extended for customization and other advanced reasons although most
applications should have little need to do this.
Thread defines a Builder API for creating and starting both
platform and virtual threads. The following are examples that use the builder:
Runnable runnable = ...
// Start a daemon thread to run a task
Thread thread = Thread.ofPlatform().daemon().start(runnable);
// Create an unstarted thread with name "duke", its start() method
// must be invoked to schedule it to execute.
Thread thread = Thread.ofPlatform().name("duke").unstarted(runnable);
// A ThreadFactory that creates daemon threads named "worker-0", "worker-1", ...
ThreadFactory factory = Thread.ofPlatform().daemon().name("worker-", 0).factory();
// Start a virtual thread to run a task
Thread thread = Thread.ofVirtual().start(runnable);
// A ThreadFactory that creates virtual threads
ThreadFactory factory = Thread.ofVirtual().factory();
Thread created with one of the public constructors inherits the daemon
status and thread priority from the parent thread at the time that the child Thread is created. The thread group is also inherited when
not provided to the constructor. When using a Thread.Builder to create a
platform thread, the daemon status, thread priority, and thread group are inherited
when not set on the builder. As with the constructors, inheriting from the parent
thread is done when the child Thread is created.
A Thread inherits its initial values of inheritable-thread-local variables (including the context class loader) from
the parent thread values at the time that the child Thread is created.
The 5-param constructor can be used to create a thread that does not inherit its initial
values from the constructing thread. When using a Thread.Builder, the
inheritInheritableThreadLocals
method can be used to select if the initial values are inherited.
Thread has an interrupted status which serves as a "request" for
code executing in the thread to "stop or cancel its current activity". The interrupted
status is set by invoking the target thread's interrupt() method. Many methods
that cause a thread to block or wait are interruptible, meaning they detect
that the thread's interrupted status is set and cause execution to return early from
the method, usually by throwing an exception.
If a thread executing Thread. or Object. is interrupted then it causes the method to throw InterruptedException.
Methods that throw InterruptedException do so after first clearing the
interrupted status. Code that catches InterruptedException should rethrow the
exception, or restore the current thread's interrupted status, with
Thread..interrupt(), before
continuing normally or handling it by throwing another type of exception. Code that
throws another type of exception with the InterruptedException as cause, or the InterruptedException as a suppressed exception, should also restore the
interrupted status before throwing the exception.
If a thread executing a blocking I/O operation on an java. is interrupted then it causes the channel to be
closed, and the blocking I/O operation to throw java.
with the thread's interrupted status set. If a thread blocked in a selection operation is interrupted then it causes the
selection operation to return early, with the thread's interrupted status set.
Code that doesn't invoke any interruptible methods can still respond to interrupt
by polling the current thread's interrupted status with
Thread..isInterrupted().
In addition to the interrupt() and isInterrupted() methods,
Thread also defines the static Thread.
method to test the current thread's interrupted status and clear it. It should be rare
to need to use this method.
null argument to a constructor
or method in this class will cause a NullPointerException to be thrown.
Implementation Note
In the JDK Reference Implementation, the virtual thread scheduler may be configured with the following system properties:
| System property | Description |
|---|---|
jdk.virtualThreadScheduler.parallelism
|
The scheduler's target parallelism. This is the number of platform threads available for scheduling virtual threads. It defaults to the number of available processors. |
jdk.virtualThreadScheduler.maxPoolSize
|
The maximum number of platform threads available to the scheduler. It defaults to 256. |
The virtual thread scheduler can be monitored and managed with the
jdk.management.VirtualThreadSchedulerMXBean management interface.
| Modifier and Type | Class and Description |
|---|---|
| public static interface | Thread.
A builder for |
| private static class | Thread.
Holder class for constants. |
| private static class | |
| public static enum | Thread.
A thread state. |
| private static class | Thread.
Helper class to generate thread identifiers. |
| private static class | Thread.
Helper class for auto-numbering platform threads. |
| public static interface | Thread.
Interface for handlers invoked when a |
| Modifier and Type | Field and Description |
|---|---|
| private Continuation | |
| private ThreadContainer | container
The thread container that this thread is in |
| private volatile ClassLoader | |
| private static volatile Thread. | |
| private volatile long | |
| private static final StackTraceElement[] | |
| private volatile StackableScope | headStackableScopes
The top of this stack of stackable scopes owned by this thread |
| private final Thread. | |
| private ThreadLocal. | |
| pack-priv volatile boolean | |
| pack-priv final Object | |
| public static final int | MAX_PRIORITY
The maximum priority that a thread can have. |
| public static final int | MIN_PRIORITY
The minimum priority that a thread can have. |
| private volatile String | |
| private static final Object | |
| private Interruptible | |
| pack-priv static final int | NO_INHERIT_THREAD_LOCALS
Characteristic value signifying that initial values for |
| public static final int | NORM_PRIORITY
The default priority that is assigned to a thread. |
| private volatile Object | parkBlocker
The argument supplied to the current call to java.util.concurrent.locks.LockSupport.park. |
| pack-priv static final long | PRIMORDIAL_TID
Thread identifier assigned to the primordial thread. |
| private Object | |
| pack-priv int | threadLocalRandomProbe
Probe hash value; nonzero if threadLocalRandomSeed initialized |
| pack-priv int | threadLocalRandomSecondarySeed
Secondary seed isolated from public ThreadLocalRandom sequence |
| pack-priv long | threadLocalRandomSeed
The current seed for a ThreadLocalRandom |
| private ThreadLocal. | |
| private final long | |
| private volatile Thread. |
| Access | Constructor and Description |
|---|---|
| pack-priv | Thread(ThreadGroup
the Thread group, can be null g, String the name of the new Thread name, int thread characteristics characteristics, Runnable the object whose run() method gets called task, long the desired stack size for the new thread, or
zero to indicate that this parameter is to be ignored. stackSize)Initializes a platform Thread. |
| pack-priv | |
| public | |
| public | |
| public | Thread(ThreadGroup
the thread group. If group, Runnable null the group
is set to the current thread's thread group.the object whose task)run method is invoked when this thread
is started. If null, this thread's run method is invoked.Initializes a new platform |
| public | |
| public | Thread(ThreadGroup
the thread group. If group, String null, the group
is set to the current thread's thread group.the name of the new thread name)Initializes a new platform |
| public | |
| public | Thread(ThreadGroup
the thread group. If group, Runnable null, the group
is set to the current thread's thread group.the object whose task, String run method is invoked when this thread
is started. If null, this thread's run method is invoked.the name of the new thread name)Initializes a new platform |
| public | Thread(ThreadGroup
the thread group. If group, Runnable null, the group
is set to the current thread's thread group.the object whose task, String run method is invoked when this thread
is started. If null, this thread's run method is invoked.the name of the new thread name, long the desired stack size for the new thread, or zero to indicate
that this parameter is to be ignored. stackSize)Initializes a new platform |
| public | Thread(ThreadGroup
the thread group. If group, Runnable null, the group
is set to the current thread's thread group.the object whose task, String run method is invoked when this thread
is started. If null, this thread's run method is invoked.the name of the new thread name, long the desired stack size for the new thread, or zero to indicate
that this parameter is to be ignored stackSize, boolean if inheritInheritableThreadLocals)true, inherit initial values for inheritable
thread-locals from the constructing thread, otherwise no initial
values are inheritedInitializes a new platform |
| Modifier and Type | Method and Description |
|---|---|
| public static int | Returns: an estimate of the number of live platform threads in the current thread's thread group and in any other thread group that has the current thread's thread group as an ancestorReturns an estimate of the number of live platform threads in the current thread's thread group and its subgroups. |
| private static void | |
| pack-priv boolean | |
| private static ThreadSleepEvent | |
| pack-priv void | |
| public final void | checkAccess()
Deprecated
for removal since 17. This method originally determined if the currently running
thread had permission to modify this thread.
Does nothing. |
| private static String | |
| pack-priv final void | |
| private static native void | |
| pack-priv void | |
| protected Object | clone()
Overrides java. Throws CloneNotSupportedException as a Thread can not be meaningfully cloned. |
| pack-priv static native Thread | |
| public static native Thread | |
| pack-priv void | |
| pack-priv void | |
| public static void | |
| private static native StackTraceElement[][] | |
| pack-priv static native void | |
| public static int | |
| private void | exit()
This method is called by the VM to give a Thread a chance to clean up before it actually exits. |
| pack-priv static native Object | |
| pack-priv static String | |
| public static Map | Returns: aMap from Thread to an array of
StackTraceElement that represents the stack trace of
the corresponding thread.Returns a map of stack traces for all live platform threads. |
| pack-priv static Thread[] | |
| pack-priv boolean | |
| public ClassLoader | Returns: the contextClassLoader for this thread, or null
indicating the system class loader (or, failing that, the
bootstrap class loader)Returns the context |
| pack-priv Continuation | |
| public static Thread. | Returns: the default uncaught exception handler for all threadsReturns the default handler invoked when a thread abruptly terminates due to an uncaught exception. |
| public long | Returns: this thread's ID
Deprecated
since 19. This method is not final and may be overridden to return a
value that is not the thread ID. Use
threadId() instead.
Returns the identifier of this Thread. |
| public final String | |
| private static native long | |
| public final int | |
| public StackTraceElement[] | Returns: an array ofStackTraceElement,
each represents one stack frame.Returns an array of stack trace elements representing the stack dump of this thread. |
| private native StackTraceElement[] | |
| public Thread. | |
| public final ThreadGroup | Returns: this thread's thread group ornullReturns the thread's thread group or |
| private static native Thread[] | |
| public Thread. | Returns: the uncaught exception handler for this threadReturns the handler invoked when this thread abruptly terminates due to an uncaught exception. |
| pack-priv StackableScope | |
| public static native boolean | |
| pack-priv ThreadLocal. | |
| pack-priv void | inheritScopedValueBindings(ThreadContainer container)
Inherit the scoped-value bindings from the given container. |
| public void | |
| private native void | |
| public static boolean | Returns: true if the current thread has been interrupted;
false otherwise.Tests whether the current thread has been interrupted. |
| public final boolean | |
| public final boolean | Returns: true if this thread is a daemon thread;
false otherwise.Tests if this thread is a daemon thread. |
| public boolean | Returns: true if this thread has been interrupted;
false otherwise.Tests whether this thread has been interrupted. |
| pack-priv boolean | |
| public final boolean | Returns: true if this thread is a virtual threadReturns |
| public final void | join(long
the time to wait in milliseconds millis)Waits at most |
| public final void | join(long
the time to wait in milliseconds millis, int 0-999999 additional nanoseconds to waitWaits at most |
| public final void | |
| public final boolean | |
| pack-priv long | |
| pack-priv Interruptible | |
| public static Thread. | Returns: A builder for creatingThread or ThreadFactory objects.Returns a builder for creating a platform |
| public static Thread. | Returns: A builder for creatingThread or ThreadFactory objects.Returns a builder for creating a virtual |
| public static void | onSpinWait()
Indicates that the caller is momentarily unable to progress, until the occurrence of one or more actions on the part of other activities. |
| pack-priv void | |
| private static native void | |
| public void | |
| pack-priv final void | |
| pack-priv static Object | |
| pack-priv static native Object[] | |
| public void | setContextClassLoader(ClassLoader
the context ClassLoader for this Thread, or null indicating the
system class loader (or, failing that, the bootstrap class loader) cl)Sets the context |
| pack-priv void | |
| pack-priv native void | |
| public final void | setDaemon(boolean
if on)true, marks this thread as a daemon threadMarks this thread as either a daemon or non-daemon thread. |
| public static void | setDefaultUncaughtExceptionHandler(Thread.
the object to use as the default uncaught exception handler.
If uehnull then there is no default handler.Set the default handler invoked when a thread abruptly terminates due to an uncaught exception, and no other handler has been defined for that thread. |
| pack-priv static void | |
| pack-priv void | |
| pack-priv final void | |
| public final synchronized void | |
| private native void | |
| pack-priv void | |
| public final void | |
| private native void | |
| pack-priv static void | |
| pack-priv static native void | |
| pack-priv void | |
| pack-priv void | |
| pack-priv void | |
| public void | setUncaughtExceptionHandler(Thread.
the object to use as this thread's uncaught exception
handler. If uehnull then this thread has no explicit handler.Set the handler invoked when this thread abruptly terminates due to an uncaught exception. |
| public static void | sleep(long
the length of time to sleep in milliseconds millis)Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds, subject to the precision and accuracy of system timers and schedulers. |
| public static void | sleep(long
the length of time to sleep in milliseconds millis, int 0-999999 additional nanoseconds to sleepCauses the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds plus the specified number of nanoseconds, subject to the precision and accuracy of system timers and schedulers. |
| public static void | |
| private static void | sleepNanos(long nanos)
Sleep for the specified number of nanoseconds, subject to the precision and accuracy of system timers and schedulers. |
| private static native void | |
| public void | |
| pack-priv void | start(ThreadContainer container)
Schedules this thread to begin execution in the given thread container. |
| private native void | |
| public static Thread | Returns: a new, and started, virtual threadthe object to run when the thread executes task)Creates a virtual thread to execute a task and schedules it to execute. |
| pack-priv ThreadLocal. | |
| pack-priv ThreadContainer | |
| public final long | |
| pack-priv ThreadLocal. | |
| pack-priv Thread. | |
| public String | Returns: a string representation of this thread.Overrides java. Returns a string representation of this thread. |
| pack-priv void | |
| pack-priv static ThreadGroup | |
| public static void | yield()
A hint to the scheduler that the current thread is willing to yield its current use of a processor. |
| private static native void |