We know that always a main thread is available in a java program. Apart this we can create our own thread and execute it also. There are two ways to create a thread :
class MyThread extends Thread { public void run() { Statements ; } }
MyThread obj=new MyThread();
When start() method is invoked by object obj, then thread starts it's execution on the object of MyThread. That means it will execute the statements inside the run() method.
Let's see a program for better understanding.
class MyThread extends Thread { public void run() { for(int i=1;i<=5;i++) { System.out.println("child thread"); } } } class ThreadDemo1 { public static void main(String args[]) { MyThread obj=new MyThread(); //thread instantiation obj.start(); //start the thread for(int i=1;i<=5;i++) { System.out.println("main thread"); }
main thread
main thread
main thread
main thread
main thread
child thread
child thread
child thread
child thread
child thread
Here the definition of MyThread class is representing a thread and the body of the run() method is representing a job. When main() is declared, main thread is created. main thread is responsible to instantiate the MyThread object. When start() method is invoked then thread MyThread will start its execution, that means run() method will be executed. After invoking start() method the for loop execution is the responsibility of main thread.
Silan Software is one of the India's leading provider of offline & online training for Java, Python, AI (Machine Learning, Deep Learning), Data Science, Software Development & many more emerging Technologies.
We provide Academic Training || Industrial Training || Corporate Training || Internship || Java || Python || AI using Python || Data Science etc