How to create a Thread?
- A thread can be created by extending the Thread class or by implementing the Runnable Interface.
- Below code shows the conventional way of creating Thread using Runnable This approach is really not the fastest way of creating a Thread because it is more verbose and requires 2 classes for Thread creation
public class ThreadCreationExample { public static void main(String[] args) { Task task = new Task(); Thread childThread = new Thread(task, "CHILD-THREAD"); childThread.start(); } } class Task implements Runnable{ @Override public void run() { System.out.println(Thread.currentThread().getName()+" is Running"); } }
- Below code shows the simplest way of creating a Thread using Lambda.
- From Java 8, Functional interfaces can be implemented using Lambda expression. So, creating a separate class for implementing the interface is not required.
- Function Interface is termed as an interface with a single method.
- Runnable Interface is a Functional Interface because it has only run() method.
public class ThreadCreation { public static void main(String[] args) { Thread childThread = new Thread(()->{ System.out.println("This is :"+ Thread.currentThread().getName()); }, "CHILD-THREAD"); System.out.println("This is :"+Thread.currentThread().getName()); childThread.start(); } }
Output
CHILD-THREAD is Running
Less verbose, Less no. of classes and moreover you could see the Thread's task inside the Thread body itself(more clarity) !!.
Comments
Post a Comment