Multithreading in Java by Implementing Runnable Interface
Multithreading is a Java feature that allows concurrent execution of two or more parts of a program for maximum utilization of CPU. Each part of such program is called a thread. So, threads are light-weight processes within a process.
As discussed in the previous post Threads can be created by using two mechanisms :
1. Extending the Thread class
2. Implementing the Runnable Interface
In this post we will understand the second method by performing multi threading by Implementing the Runnable Interface
class MultiThread implements Runnable { @Override public void run() { for (int i = 0; i < 10; i++) { System.out.println("Thread " + Thread.currentThread().getId()+ " is running"); } } } public class JavaApplication4 { public static void main(String[] args) { Thread object = new Thread(new MultiThread()); object.start(); for (int i = 0; i < 10; i++) { System.out.println("Main Thread id: " + Thread.currentThread().getId()); } } }
Output –
Main Thread id: 1 Thread 10 is running Main Thread id: 1 Main Thread id: 1 Main Thread id: 1 Thread 10 is running Thread 10 is running Thread 10 is running Thread 10 is running Main Thread id: 1 Thread 10 is running Main Thread id: 1 Main Thread id: 1 Main Thread id: 1 Main Thread id: 1 Main Thread id: 1 Thread 10 is running Thread 10 is running Thread 10 is running Thread 10 is running
Thread Class vs Runnable Interface
1. If we extend the Thread class, our class cannot extend any other class because Java doesn’t support multiple inheritance. But, if we implement the Runnable interface, our class can still extend other base classes.
2. We can achieve basic functionality of a thread by extending Thread class because it provides some inbuilt methods like yield(), interrupt() etc. that are not available in Runnable interface.