APIdia Launch Partner
Top Description Inners Fields Constructors Methods
java.lang

public Class Thread

extends Object
implements Runnable
Class Inheritance
All Implemented Interfaces
java.lang.Runnable
Known Direct Subclasses
java.util.TimerThread, java.lang.ref.Finalizer.FinalizerThread, java.lang.ref.Reference.ReferenceHandler, java.util.concurrent.DelayScheduler, java.util.concurrent.ForkJoinWorkerThread, jdk.internal.misc.InnocuousThread, java.lang.BaseVirtualThread
Imports
java.lang.ref.Reference, java.lang.reflect.Field, java.time.Duration, java.util.Map, .HashMap, .Objects, java.util.concurrent.ThreadFactory, .StructureViolationException, java.util.concurrent.locks.LockSupport, jdk.internal.event.ThreadSleepEvent, jdk.internal.misc.TerminatingThreadLocal, .Unsafe, .VM, jdk.internal.vm.Continuation, .ScopedValueContainer, .StackableScope, .ThreadContainer, jdk.internal.vm.annotation.ForceInline, .Hidden, .IntrinsicCandidate, .Stable, sun.nio.ch.Interruptible

A thread is a thread of execution in a program. The Java virtual machine allows an application to have multiple threads of execution running concurrently.

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.

Platform Threads

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.

Virtual Threads

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.

Creating And Starting Threads

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();
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();

Inheritance When Creating Threads

A 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 Interruption

A 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.sleep or Object.wait 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.currentThread().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.nio.channels.InterruptibleChannel is interrupted then it causes the channel to be closed, and the blocking I/O operation to throw java.nio.channels.ClosedByInterruptException 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.currentThread().isInterrupted().

In addition to the interrupt() and isInterrupted() methods, Thread also defines the static Thread.interrupted() method to test the current thread's interrupted status and clear it. It should be rare to need to use this method.

Null Handling

Unless otherwise specified, passing a 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 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.

Since
1.0

Nested and Inner Type Summary

Modifier and TypeClass and Description
public static interface
Thread.Builder

A builder for Thread and ThreadFactory objects.

private static class
Thread.Constants

Holder class for constants.

private static class
public static enum
Thread.State

A thread state.

private static class
Thread.ThreadIdentifiers

Helper class to generate thread identifiers.

private static class
Thread.ThreadNumbering

Helper class for auto-numbering platform threads.

public static interface
Thread.UncaughtExceptionHandler

Interface for handlers invoked when a Thread abruptly terminates due to an uncaught exception.

Field Summary

Modifier and TypeField and Description
private Continuation
private ThreadContainer
container

The thread container that this thread is in

private volatile ClassLoader
private static volatile Thread.UncaughtExceptionHandler
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.FieldHolder
private ThreadLocal.ThreadLocalMap
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 inheritable-thread-locals are not inherited from the constructing thread.

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.ThreadLocalMap
private final long
private volatile Thread.UncaughtExceptionHandler

Constructor Summary

AccessConstructor 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
Thread(String
thread name, can be null
name
,
int
thread characteristics
characteristics
,
boolean
true when bound to an OS thread
bound
)

Initializes a virtual Thread.

public
Thread()

Initializes a new platform Thread.

public
Thread(Runnable
the object whose run method is invoked when this thread is started. If null, this classes run method does nothing.
task
)

Initializes a new platform Thread.

public
Thread(ThreadGroup
the thread group. If null the group is set to the current thread's thread group.
group
,
Runnable
the object whose run method is invoked when this thread is started. If null, this thread's run method is invoked.
task
)

Initializes a new platform Thread.

public
Thread(String
the name of the new thread
name
)

Initializes a new platform Thread.

public
Thread(ThreadGroup
the thread group. If null, the group is set to the current thread's thread group.
group
,
String
the name of the new thread
name
)

Initializes a new platform Thread.

public
Thread(Runnable
the object whose run method is invoked when this thread is started. If null, this thread's run method is invoked.
task
,
String
the name of the new thread
name
)

Initializes a new platform Thread.

public
Thread(ThreadGroup
the thread group. If null, the group is set to the current thread's thread group.
group
,
Runnable
the object whose run method is invoked when this thread is started. If null, this thread's run method is invoked.
task
,
String
the name of the new thread
name
)

Initializes a new platform Thread so that it has task as its run object, has the specified name as its name, and belongs to the thread group referred to by group.

public
Thread(ThreadGroup
the thread group. If null, the group is set to the current thread's thread group.
group
,
Runnable
the object whose run method is invoked when this thread is started. If null, this thread's run method is invoked.
task
,
String
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 Thread so that it has task as its run object, has the specified name as its name, and belongs to the thread group referred to by group, and has the specified stack size.

public
Thread(ThreadGroup
the thread group. If null, the group is set to the current thread's thread group.
group
,
Runnable
the object whose run method is invoked when this thread is started. If null, this thread's run method is invoked.
task
,
String
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 true, inherit initial values for inheritable thread-locals from the constructing thread, otherwise no initial values are inherited
inheritInheritableThreadLocals
)

Initializes a new platform Thread so that it has task as its run object, has the specified name as its name, belongs to the thread group referred to by group, has the specified stackSize, and inherits initial values for inheritable thread-local variables if inheritThreadLocals is true.

Method Summary

Modifier and TypeMethod 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 ancestor
activeCount
()

Returns an estimate of the number of live platform threads in the current thread's thread group and its subgroups.

private static void
afterSleep(ThreadSleepEvent event)

Called after sleeping to commit the jdk.ThreadSleep event.

pack-priv boolean
alive()

Returns true if this thread is alive.

private static ThreadSleepEvent
beforeSleep(long nanos)

Called before sleeping to create a jdk.ThreadSleep event.

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
checkName(String name)

Throws NullPointerException if the name is null.

pack-priv final void
private static native void
pack-priv void
clearReferences()

Null out reference after Thread termination.

protected Object
clone()

Overrides java.lang.Object.clone.

Throws CloneNotSupportedException as a Thread can not be meaningfully cloned.

pack-priv static native Thread
currentCarrierThread()

Returns the Thread object for the current platform thread.

public static native Thread

Returns:

the current thread
currentThread
()

Returns the Thread object for the current thread.

pack-priv void
daemon(boolean on)

pack-priv void
dispatchUncaughtException(Throwable e)

Dispatch an uncaught exception to the handler.

public static void
dumpStack()

Prints a stack trace of the current thread to the standard error stream.

private static native StackTraceElement[][]
dumpThreads(Thread[] threads)

pack-priv static native void
public static int

Returns:

the number of threads put into the array
enumerate
(Thread[]
an array into which to put the list of threads
tarray
)

Copies into the specified array every live platform thread in the current thread's thread group and its subgroups.

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
findScopedValueBindings()

Search the stack for the most recent scoped-value bindings.

pack-priv static String
genThreadName()

Generates a thread name of the form Thread-<n>.

public static Map<Thread, StackTraceElement[]>

Returns:

a Map from Thread to an array of StackTraceElement that represents the stack trace of the corresponding thread.
getAllStackTraces
()

Returns a map of stack traces for all live platform threads.

pack-priv static Thread[]
getAllThreads()

Return an array of all live threads.

pack-priv boolean
public ClassLoader

Returns:

the context ClassLoader for this thread, or null indicating the system class loader (or, failing that, the bootstrap class loader)
getContextClassLoader
()

Returns the context ClassLoader for this thread.

pack-priv Continuation
getContinuation()

Returns the current continuation.

public static Thread.UncaughtExceptionHandler

Returns:

the default uncaught exception handler for all threads
getDefaultUncaughtExceptionHandler
()

Returns the default handler invoked when a thread abruptly terminates due to an uncaught exception.

public long

Returns:

this thread's ID
getId
()
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

Returns:

this thread's name.
getName
()

Returns this thread's name.

private static native long
public final int

Returns:

this thread's priority.
getPriority
()

Returns this thread's priority.

public StackTraceElement[]

Returns:

an array of StackTraceElement, each represents one stack frame.
getStackTrace
()

Returns an array of stack trace elements representing the stack dump of this thread.

private native StackTraceElement[]
public Thread.State

Returns:

this thread's state.
getState
()

Returns the state of this thread.

public final ThreadGroup

Returns:

this thread's thread group or null
getThreadGroup
()

Returns the thread's thread group or null if the thread has terminated.

private static native Thread[]
public Thread.UncaughtExceptionHandler

Returns:

the uncaught exception handler for this thread
getUncaughtExceptionHandler
()

Returns the handler invoked when this thread abruptly terminates due to an uncaught exception.

pack-priv StackableScope
public static native boolean

Returns:

true if the current thread holds the monitor lock on the specified object.
holdsLock
(Object
the object on which to test lock ownership
obj
)

Returns true if and only if the current thread holds the monitor lock on the specified object.

pack-priv ThreadLocal.ThreadLocalMap
pack-priv void
inheritScopedValueBindings(ThreadContainer container)

Inherit the scoped-value bindings from the given container.

public void
interrupt()

Interrupts this thread.

private native void
public static boolean

Returns:

true if the current thread has been interrupted; false otherwise.
interrupted
()

Tests whether the current thread has been interrupted.

public final boolean

Returns:

true if this thread is alive; false otherwise.
isAlive
()

Tests if this thread is alive.

public final boolean

Returns:

true if this thread is a daemon thread; false otherwise.
isDaemon
()

Tests if this thread is a daemon thread.

public boolean

Returns:

true if this thread has been interrupted; false otherwise.
isInterrupted
()

Tests whether this thread has been interrupted.

pack-priv boolean
isTerminated()

Returns true if the thread has terminated.

public final boolean

Returns:

true if this thread is a virtual thread
isVirtual
()

Returns true if this thread is a virtual thread.

public final void
join(long
the time to wait in milliseconds
millis
)

Waits at most millis milliseconds for this thread to terminate.

public final void
join(long
the time to wait in milliseconds
millis
,
int
0-999999 additional nanoseconds to wait
nanos
)

Waits at most millis milliseconds plus nanos nanoseconds for this thread to terminate.

public final void
join()

Waits for this thread to terminate.

public final boolean

Returns:

true if the thread has terminated, false if the thread has not terminated
join
(Duration
the maximum duration to wait
duration
)

Waits for this thread to terminate for up to the given waiting duration.

pack-priv long
pack-priv Interruptible
public static Thread.Builder.OfPlatform

Returns:

A builder for creating Thread or ThreadFactory objects.
ofPlatform
()

Returns a builder for creating a platform Thread or ThreadFactory that creates platform threads.

public static Thread.Builder.OfVirtual

Returns:

A builder for creating Thread or ThreadFactory objects.
ofVirtual
()

Returns a builder for creating a virtual Thread or ThreadFactory that creates virtual threads.

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
priority(int newPriority)

private static native void
public void
run()

Implements java.lang.Runnable.run.

This method is run by the thread when it executes.

pack-priv final void
runWith(Object bindings, Runnable op)

The VM recognizes this method as special, so any changes to the name or signature require corresponding changes in JVM_FindScopedValueBindings().

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 ClassLoader for this thread.

pack-priv void
setContinuation(Continuation cont)

Sets the current continuation.

pack-priv native void
setCurrentThread(Thread thread)

Sets the Thread object to be returned by Thread.currentThread().

public final void
setDaemon(boolean
if true, marks this thread as a daemon thread
on
)

Marks this thread as either a daemon or non-daemon thread.

public static void
setDefaultUncaughtExceptionHandler(Thread.UncaughtExceptionHandler
the object to use as the default uncaught exception handler. If null then there is no default handler.
ueh
)

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
setName(String
the new name for this thread.
name
)

Changes the name of this thread to be equal to the argument name.

private native void
pack-priv void
public final void
setPriority(int
the new thread priority
newPriority
)

Changes the priority of this thread.

private native void
setPriority0(int newPriority)

pack-priv static void
pack-priv static native void
pack-priv void
pack-priv void
pack-priv void
public void
setUncaughtExceptionHandler(Thread.UncaughtExceptionHandler
the object to use as this thread's uncaught exception handler. If null then this thread has no explicit handler.
ueh
)

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 sleep
nanos
)

Causes 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
sleep(Duration
the duration to sleep
duration
)

Causes the currently executing thread to sleep (temporarily cease execution) for the specified duration, subject to the precision and accuracy of system timers and schedulers.

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
sleepNanos0(long nanos)

public void
start()

Schedules this thread to begin execution.

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 thread
startVirtualThread
(Runnable
the object to run when the thread executes
task
)

Creates a virtual thread to execute a task and schedules it to execute.

pack-priv ThreadLocal.ThreadLocalMap
pack-priv ThreadContainer
public final long

Returns:

this thread's ID
threadId
()

Returns the identifier of this Thread.

pack-priv ThreadLocal.ThreadLocalMap
pack-priv Thread.State
threadState()

Returns the state of this thread.

public String

Returns:

a string representation of this thread.
toString
()

Overrides java.lang.Object.toString.

Returns a string representation of this thread.

pack-priv void
pack-priv static ThreadGroup
virtualThreadGroup()

Returns the special ThreadGroup for virtual threads.

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
Inherited from java.lang.Object:
equalsfinalizegetClasshashCodenotifynotifyAllwaitwaitwait