Java Design Pattern
Introduction to Java 10
Introduction to Java 11
Introduction to Java 12

How To Create And Run A Thread

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 :

  • • Create a class that extends from Thread class.
  • • Create a class which implements Runnable interface. Both the Thread class and Runnable interface are in java.lang package.

By extending from Thread class:

  • Then in this class, we override run() method :

  • Example:
    class MyThread extends Thread
    {
    	public void run()
    	{
    		 Statements ;
    	}
    }
  • Create an object of MyThread, hence the run() method is available for execution.

  • Example
    MyThread obj=new MyThread();
  • Then to start thread, we invoke start() method of Thread class, that is

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.


Example:
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");
		}
Output:

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.

About the Author



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






 PreviousNext