多執行緒_獲取和設定執行緒物件名稱
阿新 • • 發佈:2019-01-29
package cn.itcast_03; /* * 如何獲取執行緒物件的名稱呢? * public final String getName():獲取執行緒名稱。 * 如何設定執行緒物件的名稱呢? * public final void setName(String name):設定執行緒的名稱。 * * 針對不是繼承Thread類的子類該如何獲取執行緒名稱呢? * public static Thread currentThread():返回當前正在執行的執行緒物件 * Thread.currentThread().getName(); */ public class MyThreadDemo { public static void main(String[] args) { // 建立執行緒物件 // 無參構造+setXxx() // MyThread my1 = new MyThread(); // MyThread my2 = new MyThread(); // // // 呼叫方法設定名稱 // my1.setName("朱茵"); // my2.setName("周星星"); // // 啟動執行緒 // my1.start(); // my2.start(); // 帶參構造方法給執行緒起名字 // MyThread my1 = new MyThread("朱茵"); // MyThread my2 = new MyThread("周星星"); // // my1.start(); // my2.start(); // 我要獲取main方法所在的執行緒物件的名稱,該怎麼辦呢 System.out.println(Thread.currentThread().getName()); } } /* 名稱為什麼是:Thread-? 編號 class Thread{ private char name[]; public Thread() { init(null, null, "Thread-" + nextThreadNum(), 0); } public Thread(String name) { init(null, null, name, 0); } private void init(ThreadGroup g, Runnable target, String name, long stackSize) { // 大部分程式碼省略了 this.name = name.toCharArray(); } private static int threadInitNumber; private static synchronized int nextThreadNum() { return threadInitNumber++; } public final String getName() { return String.valueOf(name); } } class MyThread extends Thread{ public MyThread(){ super(); } } */
package cn.itcast_03;
public class MyThread extends Thread {
public MyThread() {
}
public MyThread(String name) {
super(name);
}
@Override
public void run() {
for (int x = 0; x < 30; x++) {
System.out.println(getName() + ":" + x);
}
}
}