如何在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++; } 

除非在创建Thread时指定了名称, 否则 Thread名称中的默认数值是递增的值。 Fabric扩展了Thread ,并且您传递Fabric实例以创建另一个Thread – 因此内部Thread计数器增加两次,因为在此过程中创建了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 

正如其他人所指出的那样,这只是一个递增的反击。

您的日志文件不按顺序打印线程名称的原因是因为java不保证启动线程的执行顺序

如果你想强制订单,那么你必须让线程等待彼此。 一种可能的方法是使用CountDownLatch

 private static CountDownLatch latch; public static void main(String[] args) throws InterruptedException { Thread t1 = new Thread(new Fabric()); Thread t2 = new Thread(new Fabric()); Thread t3 = new Thread(new Fabric()); // the countdown starts at 1. latch = new CountDownLatch(1); t1.start(); // the thread will wait till the countdown reaches 0. latch.await(); latch = new CountDownLatch(1); t2.start(); latch.await(); latch = new CountDownLatch(1); t3.start(); latch.await(); } public void run() { for(int i = 0; i < 2; i++) System.out.print(Thread.currentThread().getName()); // thread is done: set counter to 0. latch.countDown(); } 

另一方面,一些类使用ThreadFactory来分配线程名称。 (例如ScheduledThreadPoolExecutor )。 例如, DefaultThreadFactory创建其线程名称,如下所示:

 String namePrefix = "pool-" + poolNumber.getAndIncrement() + "-thread-"; String threadName = namePrefix + threadNumber.getAndIncrement()