fastread homefastrread library fastread menu

Java : Naming a thread

Tutorial by:Arena Buocel      Date: 2016-05-04 04:48:52

❰ Previous Next ❱

The Thread class provides methods to change and get the name of a thread.
  1. public String getName(): is used to return the name of a thread.
  2. public void setName(String name): is used to change the name of a thread.

Example of naming a thread:

 
  1. class TestMultiNaming1 extends Thread{  
  2.   public void run(){  
  3.    System.out.println("running...");  
  4.   }  
  5.  public static void main(String args[]){  
  6.   TestMultiNaming1 t1=new TestMultiNaming1();  
  7.   TestMultiNaming1 t2=new TestMultiNaming1();  
  8.   System.out.println("Name of t1:"+t1.getName());  
  9.   System.out.println("Name of t2:"+t2.getName());  
  10.    
  11.   t1.start();  
  12.   t2.start();  
  13.   
  14.   t1.setName("Sonoo Jaiswal");  
  15.   System.out.println("After changing name of t1:"+t1.getName());  
  16.  }  
  17. }  
Output:Name of t1:Thread-0
       Name of t2:Thread-1
       id of t1:8
       running...
       After changeling name of t1:Sonoo Jaiswal
       running...
     
 

The currentThread() method:

The currentThread() method returns a reference to the currently executing thread object.

Syntax of currentThread() method:

  • public static Thread currentThread(): returns the reference of currently running thread.

Example of currentThread() method:

 
  1. class TestMultiNaming2 extends Thread{  
  2.  public void run(){  
  3.   System.out.println(Thread.currentThread().getName());  
  4.  }  
  5.  }  
  6.  public static void main(String args[]){  
  7.   TestMultiNaming2 t1=new TestMultiNaming2();  
  8.   TestMultiNaming2 t2=new TestMultiNaming2();  
  9.   
  10.   t1.start();  
  11.   t2.start();  
  12.  }  
  13. }  
Output:Thread-0
       Thread-1
 

❰ Previous Next ❱


Java

Submit Your Thought, Tutorial, Articls etc.

Submit Your Information India's Number one online promotion website