How to use threads in Java

Threads allow a program to do multiple things at the same time.

Life cycle of a thread

  1. New
  2. Runnable
  3. Running
  4. Non-Runnable (Blocked)
  5. Terminated The life cycle of thread:
  • New: The thread is in a new state when you create an instance of the thread class. It remains in this state before the start() method is invoked.

  • Runnable: The thread is in a runnable state after the invocation of the start() method, but the thread is not scheduled by the scheduler.

  • Running: The thread is put in a running state once the thread scheduler selects it.

  • Non Runnable: In this state the thread is alive, but not running.

  • Terminated: A thread is in a terminated or dead state when it’s run() method exits.

How to create threads

There are two methods for creating threads:

  1. Using Thread class

  2. Using Runnable Interface

Thread Class

i) Create a thread class:

public class Myclass extends Thread

ii) Override therun() method:

public void run();

iii) Create an object of the class:

MyThread obj = new MyThread();

iv) Invoke the start() method:

obj.start();
class MyThread extends Thread{
public void run(){
System.out.println("Thread is running...");
}
public static void main(String args[]){
MyThread obj = new MyThread();
obj.start();
}
}

Using a runnable interface:

i) Create a thread class:

public class MyThread implements Runnable 

ii) Override the run() method:

public void run();

Note: We can also use @override to override run().

iii) Create an object of the class:

Thread t = new Thread(new MyThread());

Note: we use new twice because the MyThread class does not extend the thread class. We can also write the same thing as:

 Runnable r = new MyThread();
 Thread t = new Thread(r);

iv)Inoke start() method:

t.start();

Note: We use runnable interface because if a class is already a child of its parent class, it cannot extend the thread class. Hence, it can implement runnable interface.

class MyThread implements Runnable{
public void run(){
System.out.println("Thread is running...");
}
public static void main(String args[]){
MyThread r = new MyThread();
Thread t =new Thread(r);
t.start();
}
}

Similarities between thread class and runnable interface:

  1. They create a unique object of the class
  2. They have to override the run() method