Saturday, July 26, 2014

Naming a Thread

Every Thread in a class has its own name like Thread-0, Thread – 1 and so on. We can also setthe name of Thread and get name of the Thread by two methods of Thread class as, public String getName() : return the name of the thread. public void setName(String name): set the name of the thread.

Example:

public class MyThread extends Thread{
 public void run(){
   try{
       for(int i=0;i<=5;i++){
         Thread.sleep(1000);
         System.out.println("Running thread is  = "+Thread.currentThread().getName());
       }
    }catch(InterruptedException ie){}
 }
 public static void main(String[] args){
     MyThread mt1 = new MyThread();
     MyThread mt2 = new MyThread();
     MyThread mt3 = new MyThread();
     mt1.start();
     mt2.start();
     mt3.start();
 }
}
Output: 

Running thread is  = Thread-0
Running thread is  = Thread-1
Running thread is  = Thread-2
Running thread is  = Thread-1
Running thread is  = Thread-2
Running thread is  = Thread-0
Running thread is  = Thread-2
Running thread is  = Thread-0......
Note: If you haven’t set the name of the thread the default name are Thread-0,Thread-1 so on..

public class MyThread extends Thread{
   public void run() {
        try {
            for (int i = 0; i <= 5; i++) {
                Thread.sleep(1000);
                System.out.println("Running thread is  = " + Thread.currentThread().getName();
            } // currentThread() returns current executing thread
        }
        catch (InterruptedException ie) {}
    }
    
    public static void main(String[] args){
        MyThread mt1 = new MyThread();
        MyThread mt2 = new MyThread();
        MyThread mt3 = new MyThread();
        mt1.setName("One Thread");                                                           // to set the name of the thread
        mt2.setName("Two Thread");
        mt3.setName("Three Thread");
        mt1.start();
        mt2.start();
        mt3.start();
    } 
}

1 comment :