How is default new thread name given in java?
When I run this program
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() + " ");
}
}
I get output
Thread-1 Thread-5 Thread-5 Thread-3 Thread-1 Thread-3
Is there any specific reason why the threads are given names with odd numbers - 1, 3, 5... Or is it unpredictable?
new Thread(new Fabric());
Since Fabric
is a Thread, you created 2 threads here :)
JDK8 code:
/* For autonumbering anonymous threads. */
private static int threadInitNumber;
private static synchronized int nextThreadNum() {
return threadInitNumber++;
}
The default numeric value in the Thread name is an incremented value unless the name is specified when creating the Thread. Fabric
extends Thread
, and you are passing the Fabric
instance to create another Thread - thus the internal Thread counter is incremented twice as 2 threads are created during the process.
If you change the program like given below you will get the thread numbering in sequence.
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() + " ");
}
}
and the output is
Thread-0 Thread-2 Thread-2 Thread-1 Thread-0 Thread-1
链接地址: http://www.djcxy.com/p/92116.html
上一篇: 如何正确地停止Java中的线程?
下一篇: 在java中给出了默认的新线程名称?