在Java中获取当前线程的名称
可以使用以下代码获取当前线程的名称-
示例
import java.io.*;
class name_a_thread extends Thread {
@Override
public void run() {
System.out.println("Fetching the name of the current thread-");
System.out.println(Thread.currentThread().getName());
}
}
public class Demo {
public static void main (String[] args) {
name_a_thread thr_1 = new name_a_thread();
name_a_thread thr_2 = new name_a_thread();
thr_1.start();
thr_2.start();
}
}输出结果
Fetching the name of the current thread- Thread-0 Fetching the name of the current thread- Thread-1
名为“name_a_thread”的类扩展到父类Thread。它会覆盖“运行”方法,并且在调用此函数时,控制台上会显示相关消息。名为Demo的类包含主要功能,其中创建了该类的两个实例。这两个实例都使用“开始”功能调用。