As we know, whenever a Java program executes, a thread is created automatically which is coined as Main thread. The main thread is responsible for the creation and termination of other threads from beginning to the end of a program.
So, Java provides two approaches to create a thread.
1) By extending Thread Class
2) By Implementing Runnable Interface
The reason for this is that Java doesn’t allow the concept of multiple Inheritance. That means, when one uses Thread class in the creation of threads, there would be no way to extend any other class.
To overcome this problem Runnable interface is used where a child class can inherit a class and also able to use thread functionality.
A thread class allows us to manage and control any thread using its methods such as getName(),isAlive(),join()and more.
It extends object class and also implements Runnable Interface. A runnable interface that is implemented by Thread class consists of only a single method called run() method where the behavior or task of a thread is defined.
class MyFirstThread extends Thread{ @Override public void run() { int i; for(i=0;i<3;i++) { System.out.println("I am First Thread"); } } } class MySecondThread extends Thread{ @Override public void run() { int i; for(i=0;i<3;i++) { System.out.println("I am Second Thread"); } } } public class Threads1 { public static void main(String[] args) { MyFirstThread Thread1 = new MyFirstThread(); MySecondThread Thread2 = new MySecondThread(); Thread1.start(); Thread2.start(); } }
Output:
The runnable interface can’t call the run method directly. In order to move a thread to the Runnable state, start() method is used which invokes the run method whose definition is provided in Thread class. So, implementing only the Runnable interface wouldn’t work. Therefore, we need to create an object of a class and pass its reference as an argument to Thread class constructor explicitly.
class A implements Runnable { @Override public void run() { int i; for(i=0;i<5;i++) { System.out.println("I am child thread"); } } } public class ImplementRunnable { public static void main(String[] args) { A obj = new A(); Thread thread1 = new Thread(obj, "child thread"); thread1.start(); } }
Output:
run:
I am child thread
I am child thread
I am child thread
I am child thread
I am child thread
This post was last modified on December 27, 2020