Java Thread getId() 方法



描述

Java Thread getId() 方法返回此執行緒的識別符號。執行緒 ID 是在建立此執行緒時生成的正長整數。

執行緒 ID 是唯一的,在其生命週期內保持不變。當執行緒終止時,此執行緒 ID 可能會被重用。

宣告

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

public long getId()

引數

返回值

此方法返回此執行緒的 ID。

異常

示例:獲取使用 Runnable 介面建立的執行緒的 ID

以下示例演示了 Java Thread getId() 方法的使用。在此程式中,我們透過實現 Runnable 介面建立了一個名為 ThreadDemo 的類。在建構函式中,我們建立了一個新的執行緒,其預設名稱為 Admin Thread 並列印了它。使用 start() 方法啟動執行緒。在 run() 方法中,使用 getId() 列印執行緒的 ID。在 main 方法中,建立 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());
      // returns the id of this Thread.
      System.out.println("Id = " + t.getId());
   }

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

輸出

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

thread  = Thread[#21,Admin Thread,1,main]
Name = Admin Thread
Id = 21

示例:獲取使用 Thread 類建立的執行緒的 ID

以下示例演示了 Java Thread getId() 方法的使用。在此程式中,我們透過擴充套件 Thread 類建立了一個名為 ThreadDemo 的類。在建構函式中,我們建立了一個新的執行緒,其預設名稱為 Admin Thread 並列印了它。使用 start() 方法啟動執行緒。在 run() 方法中,使用 getId() 列印執行緒的 ID。在 main 方法中,建立 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());
      // returns the id of this Thread.
      System.out.println("Id = " + t.getId());
   }

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

輸出

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

thread  = Thread[#22,Admin Thread,1,main]
Name = Admin Thread
Id = 22
java_lang_thread.htm
廣告

© . All rights reserved.