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?
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.
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.
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.
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
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++;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With