Java Thread setName() 方法



描述

Java Thread setName() 方法將此執行緒的名稱更改為與引數 name 相同。

宣告

以下是 java.lang.Thread.setName() 方法的宣告

public final void setName(String name)

引數

name − 這是此執行緒的新名稱

返回值

此方法不返回任何值。

異常

SecurityException − 如果當前執行緒無法修改此執行緒。

示例:設定執行緒的名稱

以下示例演示了 Java Thread setName() 方法的使用。在此程式中,我們建立了一個類 ThreadDemo。在 main 方法中,使用 currentThread() 方法檢索當前執行緒並打印出來。使用 setName() 更改執行緒的名稱並再次列印,以及活動執行緒數。

package com.tutorialspoint;

public class ThreadDemo {

   public static void main(String[] args) {

      Thread t = Thread.currentThread();
      // prints the thread name
      System.out.println("Thread = " + t);
    
      // change the thread name
      t.setName("Admin Thread");
     
      // prints the thread after changing name
      System.out.println("Thread after changing name = " + t);
    
      int count = Thread.activeCount();
      System.out.println("currently active threads = " + count);
   }
} 

輸出

讓我們編譯並執行以上程式,這將產生以下結果:

Thread = Thread[main,5,main]
Thread after changing name = Thread[Admin Thread,5,main]
currently active threads = 1
java_lang_thread.htm
廣告