在 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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP