Defining and Creating a thread in Multithreading Java

We can Define a thread in two ways:​

  1. Extending Thread class (Approach 1)
  2. Implementing Runnable interface (Approach 2)

1. Extending Thread class: In this approach, we have to declare a class , it must be extended from java.lang.Thread class.

class MyThread extends Thread 
{ 
    --implementation---- 
}


2. Implementing Runnable interface: In this approach, we have to declare a class, it mus implement java.lang.Runnable interface.

class MyThread implements Runnable 
{
---implementation----
 }


1. Example for extending thread:
 

class MultithreadingDemo extends Thread
{
   public void run()
     {
        for(int i =0; i<5;i++)
           { 
        System.out.println("Child Thread");//job of a thread 
           }
     }
}
public class Demo1
 { 
        public static void main(String[] args) 
         {
             MultithreadingDemo mt = new MultithreadingDemo();
                mt.start(); 
            for(int i=0;i<5;i++) 
             { 
                System.out.println("Main Thread"); 
             }
         }
 }


Thread Scheduler: Its part of JVM: If multiple threads exist, then which order the threads are executed depends on JVM.
start():- method performs thread scheduling, perform other mandatory activity and invoking run() method.
Cases:
Case 1: Changing t.start() -> t.run() in main method w.r.t above program
t.start()-> A new thread is created which is responsible for the execution of run() but after replacing as run() method in main method, a new thread is not created and the run() will be executed just like a normal method caaled by main.
Case 2: Overloading of run()

class MultithreadingDemo extends Thread
{  
    public void run()
     { 
        System.out.println("normal run");//job of a thread
     } 
    public void run(int i)
     { 
       System.out.println("argument run");//job of a thread 
    }
}
public class Demo1 
    { 
       public static void main(String[] args)
        { 
          MultithreadingDemo mt = new MultithreadingDemo(); 
          mt.start(); 
         //mt.run(2); 
   }
 }


In the above example, first run will be invoked by start() method and other overloaded() should be called explicitly like normal method call.
If we are not overriding run() then thread class run() will be executed which has empty implementation. Hence no output.
Case3: If we override the start() then start() will be executed just like a normal method and new thread wont be created.

class MultithreadingDemo extends Thread
{ 
     public void start()
   {  
      System.out.println("Start");//job of a thread
   }
      public void run(int i)
  {  
      System.out.println("run");//job of a thread 
  }
}
 public class Demo1
 {
     public static void main(String[] args) 
      { 
         MultithreadingDemo mt = new MultithreadingDemo(); 
         mt.start();
         System.out.println("main thread");
      }
  }


Note: It’s not recommended to override start(), if so multithreading is not recommended.

Case 4: After starting a thread, if you are trying to restart same thread then will get run time exception -> illegal thread state exception.

2. Example of Implementing Runnable interface:
 

class MyRunnable implements Runnable
{
    public void run() 
    { 
      for(int i=0; i<5; i++)
      { 
        System.out.println("Child thread");
      }
     }
}
public class Demo2 
{
    public static void main(String[] args)
    {
      MyRunnable r= new MyRunnable(); 
     Thread t = new Thread(r);//target runnable t.start(); 
     System.out.println("Main Thread");
     } 
}


Cases:

My Runnable r= new MyRunnable(); ->runnable object
Thread t1= new Thread();-> thread object
Thread t2= new Thread(r);

Case 1:  t1.start(); ->thread class implementation empty
              Thread t = new Thread();
               t.start();
Case 2: on changing t1.run() from t1.start -> no new thread will be created executed normally
Case 3: t2.run(); //MyRunnable will be executed
           MyRunnable r= new MyRunnable();
           Thread t1= new Thread();
           Thread t2= new Thread(r);
            t2.run();
Case 4: r.start(); //compile time error(no method start() location: class MyRunnable
Case 5:  r.run //No new thread will be created under MyRunnable run() will be
executed like normal method call.

Comparision of approaches in defining thread

Approach1: Mythread->Thread->Runnable
Approach2: MyRunnable->Runnable

Which approach is best to define a thread?
Approach 1: outer class always extends thread class, there is no chance of extending any other class hence inheritance is not possible.
Approach 2: always recommended while implementing runnable interface, we can extend any other class. Hence inheritance is possible.

Posted on by