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?
Since
Fabric
is a Thread, you created 2 threads here :)JDK8 code:
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
.On the other hand, some classes use a
ThreadFactory
to assign thread names. (e.g. aScheduledThreadPoolExecutor
). For example theDefaultThreadFactory
creates its thread names as follows:If you change the program like given below you will get the thread numbering in sequence.
and the output is
The default numeric value in the Thread name is an incremented value unless the name is specified when creating the Thread.
Fabric
extendsThread
, and you are passing theFabric
instance to create another Thread - thus the internal Thread counter is incremented twice as 2 threads are created during the process.