Thread class used to create a thread which provides constructors and methods for creating and operating.
The thread class extends the object class and implements a runnable interface. The thread class considered the main class which is responsible for implementing multithreading concept in java or we can say on which Java’s multithreading system is based.
public class Test {
public static void main(String[] args) {
MyThread t1 = new MyThread();
t1.start();
for (int i = 1; i <= 5; i++) {
System.out.println("Main Thread");
}
}
}
class MyThread extends Thread {
public void run() {
for (int i = 1; i <= 5; i++) {
System.out.println("Child Thread");
}
}
}
Output
Main Thread
Main Thread
Main Thread
Child Thread
Child Thread
Child Thread
Child Thread
Child Thread
Main Thread
Main Thread
Here, we can expect the same output due thread class implementation.
By Implementing Runnable Interface
public class RunnableTest {
public static void main(String[] args) {
MyRunnable runnable = new MyRunnable();
Thread t = new Thread(runnable);
t.start();
for (int i = 1; i <= 5; i++) {
System.out.println("Main Thread");
}
}
}
class MyRunnable implements Runnable {
@Override
public void run() {
// TODO Auto-generated method stub
for (int i = 1; i <= 5; i++) {
System.out.println("Child Thread");
}
}
}
Output:
Main Thread
Main Thread
Child Thread
Child Thread
Child Thread
Child Thread
Main Thread
Main Thread
Main Thread
Child Thread
Which approach is best to define a thread?
Among two ways of difining a thread, implements Runnable approach is recommended.
In the first approach our class always extends Thread class, there is no chance of extending any other class. Hence, we are missing inheritece benefits . But, in the second approach while implementing Runnable interface, we can extend any oher class. Hence, wouldn’t miss any inheritence benefit.
Beccause of above reason, implementing Runnable interface approach is recommanded than extending Thread class.