Yes, we can do that. Let us see an example −
Example
class my_thread extends Thread{
public void run(){
try{
System.out.println ("The thread " + Thread.currentThread().getId() + " is currently running");
}
catch (Exception e){
System.out.println ("The exception has been caught");
}
}
}
public class Main{
public static void main(String[] args){
int n = 6;
for (int i=1; i<n; i++){
my_thread my_object = new my_thread();
my_object.run();
}
}
}Output
The thread 1 is currently running The thread 1 is currently running The thread 1 is currently running The thread 1 is currently running The thread 1 is currently running
A class named ‘my_thread’ inherits the main Thread, wherein a ‘run’ function is defined, that gives the id of the current thread that is being run. A try and catch block is defined that catches an exception (if any) and displays the relevant error. In the main function, a ‘for’ loop is run and new object of the ‘my_thread’ class is created. The ‘run’ function is called on this object.