Java - Multithreading & Concurrency in Java
1️⃣ What is Multithreading?
Multithreading means running multiple parts of a program (called threads) at the same time.
A thread is a lightweight unit of execution inside a program.
Instead of executing tasks one by one, Java can execute several tasks simultaneously, improving performance and responsiveness.
Example:
-
Downloading a file while playing music
-
A game updating graphics while processing user input
Each task runs in its own thread.
2️⃣ What is Concurrency?
Concurrency refers to managing multiple tasks that make progress during overlapping time periods.
It doesn’t always mean they run exactly at the same instant (that’s parallelism), but they are handled efficiently together.
In Java:
-
Multithreading → creating multiple threads
-
Concurrency → controlling and coordinating them safely
3️⃣ Why is Multithreading Important?
-
Better CPU utilization
-
Faster program execution
-
Improved responsiveness (especially in GUIs/web apps)
-
Ability to handle multiple users/tasks
4️⃣ Creating Threads in Java
There are two common ways:
✅ Method 1: Extending Thread class
class MyThread extends Thread {
public void run() {
System.out.println("Thread running");
}
}
MyThread t = new MyThread();
t.start();