Profile Photo

Java Threading

Created on: Sep 26, 2024

In Java, a thread is a lightweight unit of execution that represents a single sequential flow of control within a program and has separate paths of execution.

Different state of thread:

  1. New State
  2. Active State
  3. Waiting/Blocked State
  4. Timed Waiting State
  5. Terminated State

We can create thread by

  1. Extending Thread class
class ThreadDemo extends Thread{ @Override public void run(){ System.out.println("Thread started running "+ Thread.currentThread().getName()); } } public class Test{ public static void main(String[] args) { ThreadDemo threadDemo = new ThreadDemo(); threadDemo.start(); } }
  1. implement Runnable interface
class ThreadDemo implements Runnable{ @Override public void run(){ System.out.println("Thread started running "+ Thread.currentThread().getName()); } } public class Test{ public static void main(String[] args) { ThreadDemo threadDemo = new ThreadDemo(); Thread thread = new Thread(threadDemo, "thread-1"); thread.start(); } }

Important method in threading:

  1. Wait: Makes the current thread wait until another thread invokes notify() or notifyAll()
  2. notify: Wakes up a single thread that is waiting on the object's monitor.
  3. join: Waits for the thread to die, i.e., completes execution.
  4. sleep: Pauses the current thread for a specified amount of time (in milliseconds)

IMPORTANT POINT

  1. The low cost of communication between the processes.