Naming a thread:
The Thread class provides methods to change and get the name of a thread.
|
Example of naming a thread:
class TestMultiNaming1 extends Thread{
public void run(){
System.out.println("running...");
}
public static void main(String args[]){
TestMultiNaming1 t1=new TestMultiNaming1();
TestMultiNaming1 t2=new TestMultiNaming1();
System.out.println("Name of t1:"+t1.getName());
System.out.println("Name of t2:"+t2.getName());
t1.start();
t2.start();
t1.setName("Sonoo Jaiswal");
System.out.println("After changing name of t1:"+t1.getName());
}
}
Output:Name of t1:Thread-0Name of t2:Thread-1running...id of t1:8After changeling name of t1:Sonoo Jaiswalrunning...
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:
class TestMultiNaming2 extends Thread{
public void run(){
System.out.println(Thread.currentThread().getName());
}
}
public static void main(String args[]){
TestMultiNaming2 t1=new TestMultiNaming2();
TestMultiNaming2 t2=new TestMultiNaming2();
t1.start();
t2.start();
}
}
Output:Thread-0Thread-1
No comments:
Post a Comment