DEV Community

MGManjusha
MGManjusha

Posted on

Java Threads

What are Java Threads? Basically, Threads allows a program to operate more efficiently by doing multiple things at the same time.
To start the next task: Instead of waiting till one task ends, It will be more efficient to do multiple tasks at the same time.

The life cycle of a thread:

  1. New
  2. Runnable
  3. Running
  4. Non-Runnable (Blocked)
  5. Terminated Alt Text The life cycle of Thread in detail:

1.New: The thread is in new state when you create an instance of Thread class. it is in this stare before the invocation of start() method.

2.Runnable: The thread is in runnable state after the invocation of start() method, but the thread scheduler has not selected it to be for running.

3.Running:
The thread is in running state when the thread scheduler has selected it.

4.None Runnable: In this state the thread is alive but not in running state .

5.Terminated: A thread is in terminated or dead state when it's run() method exits.

Creation of Threads:

There are two methods for creating threads: 1. Using Thread class

  1. Using Runnable Interface

In detail:

  1. Using Thread class: STEPS:-

i) Create a Thread class:

public class Myclass extends Thread
Enter fullscreen mode Exit fullscreen mode

ii) Override run() method:

public void run();
Enter fullscreen mode Exit fullscreen mode

iii) Create object of class:

MyThread obj = new MyThread();
Enter fullscreen mode Exit fullscreen mode

iv)Invoke start() method:

obj.start();
Enter fullscreen mode Exit fullscreen mode

Example:
Alt Text

  1. Using Runnable Interface: STEPS:

i) Create a thread class:

public class MyThread implements Runnable 
Enter fullscreen mode Exit fullscreen mode

ii) Override run() method:

public void run();
Enter fullscreen mode Exit fullscreen mode

important point: We can also use '@override' to override the run()

iii) Create object of the class:

Thread t = new Thread(new MyThread());
Enter fullscreen mode Exit fullscreen mode

Note: we use new twice because MyThread class does not extend Thread class
and we can also write the same thing as:

 Runnable r = new MyThread();
 Thread t = new Thread(r);
Enter fullscreen mode Exit fullscreen mode

iv)Inoke start() method:

t.start();
Enter fullscreen mode Exit fullscreen mode

Note: We use runnable interface because if a class is already a child of its parent class it cannot extend Thread class and hence it can implement Runnable Interface.

Example:
Alt Text

Similarities between Thread class and Runnable Interface:

  1. Both create a unique object of the class
  2. Both consumes more memory
  3. Both have to override the run() method

Top comments (0)