在java中给出了默认的新线程名称?
当我运行这个程序
public class Fabric extends Thread {
public static void main(String[] args) {
Thread t1 = new Thread(new Fabric());
Thread t2 = new Thread(new Fabric());
Thread t3 = new Thread(new Fabric());
t1.start();
t2.start();
t3.start();
}
public void run() {
for(int i = 0; i < 2; i++)
System.out.print(Thread.currentThread().getName() + " ");
}
}
我得到输出
Thread-1 Thread-5 Thread-5 Thread-3 Thread-1 Thread-3
是否有任何具体的原因,为什么线程被赋予奇数的名称 - 1,3,5 ......还是它是不可预测的?
new Thread(new Fabric());
由于Fabric
是一个线程,所以你在这里创建了2个线程:)
JDK8代码:
/* For autonumbering anonymous threads. */
private static int threadInitNumber;
private static synchronized int nextThreadNum() {
return threadInitNumber++;
}
除非在创建线程时指定名称,否则线程名称中的默认数值是递增值。 Fabric
扩展了Thread
,并且您正在传递Fabric
实例以创建另一个线程 - 因此内部线程计数器会在进程中创建2个线程时递增两次。
如果您更改程序,如下所示,您将按顺序获得线程编号。
public class Fabric extends Thread {
public static void main(String[] args) {
Thread t1 = new Fabric();
Thread t2 = new Fabric();
Thread t3 = new Fabric();
t1.start();
t2.start();
t3.start();
}
public void run() {
for(int i = 0; i < 2; i++)
System.out.print(Thread.currentThread().getName() + " ");
}
}
和输出是
Thread-0 Thread-2 Thread-2 Thread-1 Thread-0 Thread-1
链接地址: http://www.djcxy.com/p/92115.html
上一篇: How is default new thread name given in java?
下一篇: Use of thread in Java class without implementing Runnable nor extending Thread