How to create a Thread?

  1. A thread can be created by extending the Thread class or by implementing the Runnable Interface. 
  2. 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");
    }
}

  1. Below code shows the simplest way of creating a Thread using Lambda.
  2. From Java 8, Functional interfaces can be implemented using Lambda expression. So, creating a separate class for implementing the interface is not required.
  3. Function Interface is termed as an interface with a single method. 
  4. Runnable Interface is a Functional Interface because it has only run() method. 
 Lambda expression can be simply put as (method arguments) -> { body of the 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

    Popular posts from this blog

    Distributed database design using CAP theorem

    SQL Analytical Functions - Partition by (to split resultset into groups)

    Easy approach to work with files in Java - Java NIO(New input output)