Saturday, 29 June 2019

Getting and setting name of a Thread

  • Every Thread in java has some name it may be provided explicitly by the programmer or automatically generated by JVM.
  • Thread class defines the following methods to get and set name of a Thread.
Methods:
  1. public final String getName()
  2. public final void setName(String name)
Example: 


class MyThread extends Thread
{}
class ThreadDemo
{
              public static void main(String[] args)
              {
                             System.out.println(Thread.currentThread().getName());//main
                             MyThread t=new MyThread();
                             System.out.println(t.getName());//Thread-0
                             Thread.currentThread().setName("PKN Thread");

                             System.out.println(Thread.currentThread().getName());//PKN Thread
              }
}


Note: We can get current executing Thread object reference by using Thread.currentThread() method.


Thanks..!!

No comments:

Post a Comment