🌟 What is Multithreading in Java?
Multithreading in Java is a process of executing multiple threads
simultaneously. A thread is the smallest unit of execution in a program.
Multithreading allows:
Efficient CPU utilization.
Better performance for programs with multiple tasks.
Parallel execution of code.
🔁 Difference Between Process and Thread
Feature Process Thread
Definition An independent program A smaller unit of a process
Memory Each process has its own memory Shares memory with other threads
Communic-
Complex Easy (since memory is shared)
-ation
Overhead More Less
Example Chrome, Word Tabs in Chrome, background tasks
, 🧵 Life Cycle of a Thread
Java threads go through five stages:
Stage Description
New Thread is created using a constructor
Runnable Thread is ready to run but waiting for CPU
Running Thread is executing
Blocked Thread is waiting to acquire a lock
Terminated Thread has finished execution or has been stopped
(Image for reference only)
🛠️Creating Threads in Java
Java provides two main ways to create threads:
1. By extending the Thread class
java
CopyEdit
class MyThread extends Thread {
public void run() {
System.out.println("Thread running...");
}
public static void main(String[] args) {
MyThread t1 = new MyThread();
t1.start(); // starts the thread
}
}
2. By implementing the Runnable interface
java
CopyEdit
class MyRunnable implements Runnable {
public void run() {
System.out.println("Runnable thread running...");
}
public static void main(String[] args) {
Thread t = new Thread(new MyRunnable());
t.start();
}
}