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 –
- Create a class and extend Thread
- Override the run() method.
- Instantiate the class
- 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 –
- Create a class and implement Runnable interface
- Implement the run() method.
- Instantiate Runnable class
- Instantiate the Thread class, pass Runnable class in Thread’s Constructor
- 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();
}
}