Java获取线程名称的方法

    科技2025-10-30  8

    J a v a Java Java获取线程名称的方法

    通过 g e t N a m e ( ) getName() getName()方法即可。 另外: c u r r e n t T h r e a d ( ) currentThread() currentThread()是获取当前线程的引用的一种静态方法。

    T h r e a d Thread Thread子类

    public class MyThread extends Thread{ @Override public void run() { System.out.println(getName()); // Thread t = Thread.currentThread(); // System.out.println("当前的线程"+t);//[Thread-x,5,main] } }

    主方法:

    public class Test { public static void main(String[] args) { MyThread mt = new MyThread(); mt.start(); new MyThread().start(); new MyThread().start(); new MyThread().start(); System.out.println(Thread.currentThread().getName()); } }

    输出结果:

    Thread-0 main Thread-1 Thread-3 Thread-2
    Processed: 0.022, SQL: 8