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
廣告