在Java程式設計中,如何獲取正在執行的執行緒的名稱?
以下範例顯示如何獲取正在執行的執行緒的名稱。
package com.yiibai;
public class GettingThreadName extends Thread {
public void run() {
for (int i = 0; i < 10; i++) {
printMsg();
}
}
public void printMsg() {
Thread t = Thread.currentThread();
String name = t.getName();
System.out.println("name = " + name);
}
public static void main(String[] args) {
GettingThreadName tt = new GettingThreadName();
tt.start();
for (int i = 0; i < 10; i++) {
tt.printMsg();
}
}
}
上述程式碼範例將產生以下結果 -
name = main
name = Thread-0
name = main
name = Thread-0
name = main
name = Thread-0
name = main
name = main
name = main
name = main
name = Thread-0
name = Thread-0
name = Thread-0
name = Thread-0
name = Thread-0
name = Thread-0
name = main
name = Thread-0
name = main
name = main