Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 946
Jeet Parekh Avatar asked May 29 '15 16:05

Jeet Parekh


People also ask

How to change the thread name in Java?

Java provides some methods to change the thread name. There are basically two methods to set the thread name. Both methods are defined in java.lang.Thread class. Setting the thread’s name directly: We can set the thread name at time of creating the thread and by passing the thread’s name as an argument. // the Thread class.

How to create a thread in Java?

Note that there is only one way to create a thread and that's to instantiate Thread and start the instance. The two things you describe implementing Runnable interface and by extending Thread class are ways to define the behavior of the executing thread. Both your code snippets are examples of the first method, implementing Runnable.

What is the use of start () method of Thread class?

The start () method of Thread class is used to start a newly created thread. It performs the following tasks: A new thread starts (with new callstack). The thread moves from New state to the Runnable state. When the thread gets a chance to execute, its target run () method will run.

How to see all threads in a Java program?

2 If you have the JDK installed you can use jvisualvmor jconsole(older versions of Java) located in the bin (Windows) directory. The tool will allow you to see all the threads and their details. Screenshot attached. Share Follow answered Apr 11, 2011 at 9:31


1 Answers

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++;
}
like image 166
ZhongYu Avatar answered Sep 28 '22 11:09

ZhongYu