Java Thread getName() 方法



描述

Java Thread getName() 方法返回此线程的名称。

声明

以下是 java.lang.Thread.getName() 方法的声明

public final String getName()

参数

返回值

此方法返回此线程的名称。

异常

示例:获取使用 Runnable 接口创建的线程的名称

以下示例演示了 Java Thread getName() 方法的用法。在这个程序中,我们通过实现 Runnable 接口创建了一个名为 ThreadDemo 的类。在构造函数中,我们创建了一个名为“Admin Thread”的新线程并打印出来。使用 start() 方法启动线程。在 run() 方法中,使用 getName() 打印线程的名称。在主方法中,创建 ThreadDemo 对象。

package com.tutorialspoint;

public class ThreadDemo implements Runnable {

   Thread t;
   ThreadDemo() {
    
      // thread created
      t = new Thread(this, "Admin Thread");
      
      // set thread priority
      t.setPriority(1);
      
      // print thread created
      System.out.println("thread  = " + t);
      
      // this will call run() function
      t.start();
   }

   public void run() {
      // returns the name of this Thread.
      System.out.println("Name = " + t.getName());
   }

   public static void main(String args[]) {
      new ThreadDemo();
   }
} 

输出

让我们编译并运行上面的程序,这将产生以下结果:

thread = Thread[Admin Thread,1,main]
Name = Admin Thread

示例:获取使用 Thread 类创建的线程的名称

以下示例演示了 Java Thread getName() 方法的用法。在这个程序中,我们通过继承 Thread 类创建了一个名为 ThreadDemo 的类。在构造函数中,我们创建了一个名为“Admin Thread”的新线程并打印出来。使用 start() 方法启动线程。在 run() 方法中,使用 getName() 打印线程的名称。在主方法中,创建 ThreadDemo 对象。

package com.tutorialspoint;

public class ThreadDemo extends Thread {

   Thread t;
   ThreadDemo() {
    
      // thread created
      t = new Thread(this, "Admin Thread");
      
      // set thread priority
      t.setPriority(1);
      
      // print thread created
      System.out.println("thread  = " + t);
      
      // this will call run() function
      t.start();
   }

   public void run() {
      // returns the name of this Thread.
      System.out.println("Name = " + t.getName());
   }

   public static void main(String args[]) {
      new ThreadDemo();
   }
} 

输出

让我们编译并运行上面的程序,这将产生以下结果:

thread = Thread[Admin Thread,1,main]
Name = Admin Thread
java_lang_thread.htm
广告
© . All rights reserved.