- 使用Thread类中的方法
getName()
String getName()
返回该线程的名称。 - 可以先获取到当前正在执行的线程,使用线程中的方法getName()获取线程的名称
static Thread currentThread()
返回对当前正在执行的线程对象的引用。
public class MyThread extends Thread {
@Override
public void run() {
String name = getName();
System.out.println("getName()获取线程名:" + name);
Thread currentThread = Thread.currentThread();
System.out.println(currentThread);
System.out.println(currentThread.getName());
}
}
public class DemoThread {
public static void main(String[] args) {
new MyThread().start();
new MyThread().start();
Thread thread = Thread.currentThread();
System.out.println("main方法线程:"+thread);
}
}
main方法线程:Thread[main,5,main]
getName()获取线程名:Thread-0
getName()获取线程名:Thread-1
Thread[Thread-0,5,main]
Thread[Thread-1,5,main]
Thread-1
Thread-0