Defining a thread :
We can define a thread in the following two ways :
a. By extending Thread class
b. By implementing runnable interface.
By implementing runnable interface.
- Runnable interface is present in java.lang package and it contains one method called public void run() method.
- The major difference between Thread class and Runnable Interface is that Thread class is the class which has the ability to create Threads in java but Runnable Interface is just an interface which helps to define the job which has to be executed by a Thread using the run method.
- We can pass an object of a class which implements Runnable interface to the constructor a Thread class object and call the Thread class’s start method to start a new child thread.
- Since runnable interface is just used to create the job which has to be executed by a Thread we cannot specifiy the name of the thread using Runnable interface, we can give name to a thread when we pass the reference of the class that implements Runnable interface into the Thread constructor or by setName() method of the Thread class
Thread t = new Thread(runnableObject,”My Thread Name”);
t.setName(“My Thread Name”);
package com.demo2; import java.util.stream.IntStream; class MyRunnable implements Runnable{ @Override public void run() { IntStream.range(1,10).forEach(x -> System.out.println("Child Thread : "+x)); } } public class ThreadDemo { public static void main(String[] args) { Thread t = new Thread(new MyRunnable()); t.start(); IntStream.range(1,10).forEach(x -> System.out.println("Main Thread : "+x)); } }
Among the two ways to defining a thread, the implementing Runnable interface approach is suggest because the class implementing Runnable method still has a scope to extend another class but a class extending Thread class cannot support this functionality.