在 Java 中獲取當前執行緒


可以透過實現 Runnable 介面並重寫 run() 方法建立執行緒。

當前執行緒是 Java 中當前執行的執行緒物件。Thread 類的 currentThread() 方法可用於獲取當前執行緒。此方法不需要任何引數。

演示此內容的程式如下所示 −

示例

 即時演示

public class Demo extends Thread {
   public void run() {
      for (int i = 0; i < 5; i++) {
         System.out.println("The Thread name is " + Thread.currentThread().getName());
      }
   }
   public static void main(String[] args) {
      Demo t1 = new Demo();
      t1.setName("Main Thread");
      t1.start();
      Thread t2 = currentThread();
      t2.setName("Current Thread");
      for (int i = 0; i < 5; i++) {
         System.out.println("The Thread name is " + t1.currentThread().getName());
      }
   }
}

輸出

上述程式輸出如下 −

The Thread name is Current Thread
The Thread name is Current Thread
The Thread name is Current Thread
The Thread name is Current Thread
The Thread name is Current Thread
The Thread name is Main Thread
The Thread name is Main Thread
The Thread name is Main Thread
The Thread name is Main Thread
The Thread name is Main Thread

更新於: 30-Jun-2020

14K+ 瀏覽

開啟你的 事業

完成課程,取得認證

開始
廣告
© . All rights reserved.