2 回答

TA貢獻1810條經驗 獲得超4個贊
如果讓 JRE 選擇名稱(不將name參數傳遞給Threadctor),則只需遍歷其代碼:
Thread#Thread() 代碼:
public Thread() {
init(null, null, "Thread-" + nextThreadNum(), 0);
}
然后看看Thread#nextThreadNum:
/* For autonumbering anonymous threads. */
private static int threadInitNumber;
private static synchronized int nextThreadNum() {
return threadInitNumber++;
}
你可以看到這threadInitNumber是一個static永遠不會被重置的成員,所以它會隨著應用程序運行而不斷增加。

TA貢獻1871條經驗 獲得超13個贊
如果您使用以下命令創(chuàng)建新線程:
Thread thread = new Thread();
答案是肯定的,至少在環(huán)境方面:
java version "10.0.1" 2018-04-17
Java(TM) SE Runtime Environment 18.3 (build 10.0.1+10)
Java HotSpot(TM) 64-Bit Server VM 18.3 (build 10.0.1+10, mixed mode)
源代碼清楚地顯示了它:
public Thread() {
init(null, null, "Thread-" + nextThreadNum(), 0);
}
private static synchronized int nextThreadNum() {
return threadInitNumber++;
}
但這在 API 中并沒有保證,所以如果你真的關心它,你可以自定義一個線程工廠。例如:
import java.util.concurrent.ThreadFactory;
public class DefaultThreadFactory implements ThreadFactory {
private static int threadInitNumber;
private static synchronized int nextThreadNum() {
return threadInitNumber++;
}
@Override
public Thread newThread(Runnable r) {
return new Thread("Thread-" + nextThreadNum());
}
}
添加回答
舉報