java tutorial - Naming Thread and Current Thread - java programming - learn java - java basics - java for beginners

Learn Java - Java tutorial - Naming a thread - Java examples - Java programs
Naming Thread
- Thread class provides methods to alter then it get the name of the thread.
- By default, each thread have a name i.e. thread-0, thread-1 and so on.
- We can change the name of the thread by using the setName() method.
Syntax
Method | Description |
---|---|
public String getName() | Used to return the name of a thread. |
public void setName(String name) | Used to change the name of a thread. |
Sample Code
public class MultiNaming extends Thread{
public void run(){
System.out.println("Welcome to wikitechy tutorials!!!...");
}
public static void main(String args[]){
MultiNaming time1=new MultiNaming();
MultiNaming time2=new MultiNaming();
System.out.println("Name of t1:"+time1.getName());
System.out.println("Name of t2:"+time2.getName());
time1.start();
time2.start();
time1.setName("John Haakley");
System.out.println("After changing name of t1:"+time1.getName());
}
}
click below button to copy the code. By - java tutorial - team
Name of t1:Thread-0
Name of t2:Thread-1
After changing name of t1:John Haakley
Welcome to wikitechy tutorials!!!...
Welcome to wikitechy tutorials!!!...
Current Thread
- The currentThread() method returns a reference of presently executing thread.
Syntax
Sample Code
public class MultiNaming1 extends Thread{
public void run(){
System.out.println(Thread.currentThread().getName());
}
public static void main(String args[]){
MultiNaming1 time1=new MultiNaming1();
MultiNaming1 time2=new MultiNaming1();
time1.start();
time2.start();
}
}
click below button to copy the code. By - java tutorial - team
Output
Thread-1
Thread-0