How is default new thread name given in java?

前端 未结 4 1735
无人及你
无人及你 2020-12-11 03:55

When I run this program

public class Fabric extends Thread {
    public static void main(String[] args) {
        Thread t1 = new Thread(new Fabric());
              


        
4条回答
  •  既然无缘
    2020-12-11 04:53

    As others have pointed out, it's just an incrementing counter.

    The reason why your log file does not print your thread names in order, is because java does not guarentee the order of execution of the started threads.

    If you want to force the order, then you have to make the threads wait for eachother. A possible way to do this, is using a 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();
    }
    

    On the other hand, some classes use a ThreadFactory to assign thread names. (e.g. a ScheduledThreadPoolExecutor). For example the DefaultThreadFactory creates its thread names as follows:

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

提交回复
热议问题