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:
- New State
- Active State
- Waiting/Blocked State
- Timed Waiting State
- Terminated State
We can create thread by
- 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(); } }
- 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:
- Wait: Makes the current thread wait until another thread invokes
notify()ornotifyAll() - notify: Wakes up a single thread that is waiting on the object's monitor.
- join: Waits for the thread to die, i.e., completes execution.
- sleep: Pauses the current thread for a specified amount of time (in milliseconds)
IMPORTANT POINT
- The low cost of communication between the processes.
