Introduction
In java, threads refer to the path that a code follows during its execution. The Java Virtual Machine (J.V.M.) creates the main thread at the start of the program when the main() method of the program is invoked.
We can perform a single task using the multiple threads by writing a single run() method for all the threads.
Programs For Performing a Single Task by Multiple Threads
Code 1:-
class Main extends Thread{
public void run(){
System.out.println("Single Task");
}
public static void main(String args[]){
Main thread1=new Main();
Main thread2=new Main();
Main thread3=new Main();
thread1.start();
thread2.start();
thread3.start();
}
}
Output:
Practice by yourself on java online compiler.
Code 2:-
class Main extends Thread{
public void run(){
System.out.println("Single Task");
}
public static void main(String args[]){
//Making a thread using the Thread class and anonymous object.
Thread thread1=new Thread(new Main()); // passing an anonymous object
Thread thread2=new Thread(new Main());
Thread thread3=new Thread(new Main());
thread1.start();
thread2.start();
thread3.start();
}
}
Output:
We need to notice above that all the threads are running in the different call stacks, which can be seen in the following picture.
Also see, Duck Number in Java and Hashcode Method in Java