CKTIS / Java
Thread.setName — rename a thread
Give worker threads names such as `worker1`, `worker2`, and `worker3` so you can tell them apart in logs and while debugging.
Version: Java SE 21
Syntax
public final void setName(String name)
thread.setName("worker1");In Java SE 21, Thread.setName is an instance method on java.lang.Thread. It takes one String and returns nothing (void). Call it on an existing platform or virtual thread, before start() or while the thread is running. Renaming a thread does not start it or change its priority.
Use getName() to read the Java thread name. From inside a worker, use Thread.currentThread().getName() to read that worker’s own name. Names such as worker1 are useful diagnostic labels, but they need not be unique. An unnamed virtual thread returns an empty string from getName().
null is not a valid name and causes a NullPointerException. The method calls checkAccess() on the target thread first. If an installed security manager denies access, the call fails with a SecurityException.
Do not assume the Java name is also the operating-system thread name. The JDK reference implementation sets the OS name when a platform thread renames itself and was not attached to the VM through the JNI AttachCurrentThread function. Do not rely on that implementation detail for portable code.
Examples
public class WorkerNames {
public static void main(String[] args) throws InterruptedException {
for (int i = 1; i <= 3; i++) {
Thread worker = new Thread(() ->
System.out.println(Thread.currentThread().getName())
);
worker.setName("worker" + i);
worker.start();
worker.join();
}
}
}Result
worker1 worker2 worker3
Each platform thread is named before `start()` and prints its own name. `join()` waits for it to finish before the next worker starts, so the output order does not depend on scheduling.
Related lessons
- Java · Lesson 49 · Intermediate · Version: 2