当我运行这个程序时
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.或者是不可预测的?
发布于 2015-05-29 16:09:19
new Thread(new Fabric());因为Fabric是一个线程,所以您在这里创建了两个线程:)
JDK8代码:
/* For autonumbering anonymous threads. */
private static int threadInitNumber;
private static synchronized int nextThreadNum() {
return threadInitNumber++;
}发布于 2015-05-29 16:09:41
线程名称中的默认数值是一个递增的值,除非在创建线程时指定了名称。Fabric扩展了Thread,您正在传递Fabric实例来创建另一个线程--因此,在进程中创建2个线程时,内部线程计数器会增加两次。
发布于 2015-05-29 16:12:45
如果您像下面这样更改程序,您将得到线程编号的顺序。
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-1https://stackoverflow.com/questions/30534164
复制相似问题