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个赞
如果您使用以下命令创建新线程:
Thread thread = new Thread();
答案是肯定的,至少在环境方面:
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());
}
}
添加回答
举报