Create Threads in Java

By Himanshu Sharma


Multithreading can be viewed as a digital world’s term for multi-tasking. When someone say they are multitasking, they are performing multiple different tasks within a timeframe.

Even though it is an advanced topic, its use can be observed in our day-to-day basic tasks –

Multi-tasking in Java can be achieved using Threads and thus the word Multithreading since Threads are responsible for performing multiple tasks in hand.

Let’s start with some basic Thread definition and approaches to create Threads in Java.

Thread:

A thread can be viewed as a lightweight representative (sub-process) of a process. A process can generate one or more threads in order to achieve the desired result. In above examples, text editor and video players are processes.

One of the below three approaches can be used to create thread in Java.

Lambda Expression:


  Thread lambdaThread = new Thread(() -> {
      Thread.currentThread().setName("Lambda-Thread");
      System.out.println("Printing message from Lambda Thread :: "  + Thread.currentThread().getName());
  });
 

Extend Thread Class:


  class CustomThread extends Thread {
  
    @Override
    public void run() {
      this.setName("Custom-Thread");
      System.out.println("Printing message from Custom Thread :: "  + this.getName());
    }
  }
 

Implement Runnable Interface:


  class RunnableThread implements Runnable {
  
    @Override
    public void run() {
      Thread.currentThread().setName("Runnable-Thread");
      System.out.println("Printing message from Runnable Thread :: "  + Thread.currentThread().getName());
    }
  }
 

Above code snippets will allow us to create Thread, but we still have to start these threads in order to execute the code defined in run() method. And for that we need to create objects of our Thread classes (except Lambda approach) and initiate start() method. Refer below code snippet for the same.


  CustomThread customThread = new CustomThread();
  Thread runnableThread = new Thread(new RunnableThread());
  
  customThread.start();
  lambdaThread.start();
  runnableThread.start();
 

If you observe there are some subtle differences-