Java Thread currentThread() 方法



描述

Java Thread currentThread() 方法返回對當前正在執行的執行緒物件的引用。

宣告

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

public static Thread currentThread()

引數

返回值

此方法返回當前正在執行的執行緒。

異常

示例:在多執行緒程式中獲取當前執行緒

以下示例演示了 Java Thread currentThread() 方法的用法。在此示例中,我們透過實現 Runnable 介面建立了一個執行緒類 ThreadDemo。在 ThreadDemo 建構函式中,使用 currentThread 方法檢索當前活動的執行緒,建立一個新執行緒並列印兩者。

package com.tutorialspoint;

public class ThreadDemo implements Runnable {

   ThreadDemo() {
      // main thread
      Thread currThread = Thread.currentThread();
      
      // thread created
      Thread t = new Thread(this, "Admin Thread");
   
      System.out.println("current thread = " + currThread);
      System.out.println("thread created = " + t);
      
      // this will call run() function
      t.start();
   }

   public void run() {
      System.out.println("This is run() method");
   }

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

輸出

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

current thread = Thread[main,5,main]
thread created = Thread[Admin Thread,5,main]
This is run() method

示例:在單執行緒程式中獲取當前執行緒

以下示例演示了 Java Thread currentThread() 方法的用法。在此示例中,我們建立了一個執行緒類 ThreadDemo。在 main 方法中,使用 currentThread 方法檢索當前活動的執行緒,並將其打印出來。

package com.tutorialspoint;

public class ThreadDemo {

   public static void main(String[] args) {

      Thread t = Thread.currentThread();
      System.out.println("current thread = " + currThread);
   }
}   

輸出

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

current thread = Thread[#1,main,5,main]
java_lang_thread.htm
廣告