📅  最后修改于: 2020-09-27 01:15:58             🧑  作者: Mango
Thread类提供了更改和获取线程名称的方法。默认情况下,每个线程都有一个名称,即线程0,线程1等。通过使用setName()方法,我们可以更改线程的名称。 setName()和getName()方法的语法如下:
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-0
Name of t2:Thread-1
id of t1:8
running...
After changeling name of t1:Sonoo Jaiswal
running...
currentThread()方法返回当前正在执行的线程的引用。
public static Thread currentThread()
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-0
Thread-1