Java Thread setName() Method
Example
Give a thread a name, and print the name from inside the thread:
public class Main {
static class MyThread extends Thread {
public void run() {
System.out.println("Hello from " + getName());
}
}
public static void main(String[] args) {
MyThread thread = new MyThread();
thread.setName("Thread 1");
thread.start();
}
}
Definition and Usage
The setName() method changes the name of a thread.
Names make it easier to see which thread does what, for example when you print messages from several threads.
Tip: Use the getName() method to get the name of a thread.
Syntax
public final void setName(String name)
Parameter Values
| Parameter | Description |
|---|---|
| name | Required. The new name of the thread. |
Related Pages
❮ Thread Methods