How many ways we can create a thread in Java? Explain with pseudo code.

There are two ways we can create a thread in multithreading in java programs that is by extending thread class and implementing Runnable interface.
Here are simple steps to create threads in java for both ways i.e. by extending Thread class and Runnbale Interface.

First way : By extending Thread Class

Steps –

  1. Create a class and extend Thread
  2. Override the run() method.
  3. Instantiate the class
  4. Call start() method

Java Code Example :

//Step 1.    Create a class and extend Thread class
public class ThreadExtended extends Thread {

//Step 2.    Override the run() method.
public void run() {
System.out.println("\nThread is running now\n");
}


/*-------------------------------------------------------------------------
* Test here
*/
public static void main(String[] args) {

//Step 3.    Instantiate the class
ThreadExtended threadE = new ThreadExtended();
//Step 4.    Call start() method
threadE.start();
}

}
Second way : By Implementing Runnable Interface

Steps –

  1. Create a class and implement Runnable interface
  2. Implement the run() method.
  3. Instantiate Runnable class
  4. Instantiate the Thread class, pass Runnable class in Thread’s Constructor
  5. Call start() method

Java Code Example :

//Step 1.    Create a class and implement Runnable interface
public class ImplementRunnable implements Runnable {

//Step 2.    Implement the run() method    
    @Override
    public void run() {
        
        System.out.println("\nThread is running now\n");
    }
        
    
    /*-------------------------------------------------------------------------
     * Test here
     */
    public static void main(String[] args) {
        
  //Step 3.    Instantiate Runnable class
        ImplementRunnable r = new ImplementRunnable();
        
  //Step 4.    Instantiate the Thread class, pass Runnable class in Thread’s Constructor            
        Thread t = new Thread(r);
        
  //Step 5.    Call start() method, start method internally calls run() method overriden in class   
        t.start();
    }    
}


Related Posts