We can get and set name of thread by using following two methods of Thread class.
- public final string getName()
- public final void setName(String name)
currentThread().getName()
Method to get name of current thread.
Every thread in java have some name provided by JVM as Thread-0,Thread-1……Thread-n.
Syntax:
1 |
Thread.currentThread().getName() |
Example to get a name of current thread
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
class MyThread extends Thread { public void run() { System.out.println("Child thread name: " +Thread.currentThread().getName()); } } class Main { public static void main(String[] args) { MyThread t=new MyThread(); System.out.println("Before starting a child thread: "+Thread.currentThread().getName()); t.start(); System.out.println("After starting a new thread:"+Thread.currentThread().getName()); } } |
Output
1 2 3 |
Before starting a child thread: main After starting a new thread:main Child thread name: Thread-0 |
currentThread().setName()
Method to set name of a thread. We can change name of current thread as follow. We also can change name of “main” thread.
Syntax:
1 |
Thread.currentThread().setName("myThread") |
Example to change name of current thread
1 2 3 4 5 6 7 8 9 |
class Main { public static void main(String[] args) { System.out.println("Current thread name: "+Thread.currentThread().getName()); Thread.currentThread().setName("myThread"); System.out.println("After changing name: "+Thread.currentThread().getName()); } } |
Output
1 2 |
Current thread name: main After changing name: myThread |