An Introduction to Java Multithreading Concepts
What is Multithreading?
Multithreading is a technique in which multiple tasks run simultaneously within the same program. It allows efficient utilization of CPU by executing multiple threads independently.
Example
Think of a web browser , You can open multiple tabs, and each tab runs independently while still being part of the same browser process.
🔹 Control Flow in Multithreading
In multithreading, we have more than one control flow, meaning multiple tasks can execute at the same time.
Threads can be created using:
Thread class
Runnable interface
Creating a Thread
🔹 Using Thread Class:
class MyThread extends Thread {
public void run() {
System.out.println("Thread is running...");
}
}
public class Test {
public static void main(String[] args) {
MyThread t = new MyThread();
t.start();
}
}
🔹Using Runnable Interface:
class MyRunnable implements Runnable {
public void run() {
System.out.println("Thread is running...");
}
}
public class Test {
public static void main(String[] args) {
MyRunnable r = new MyRunnable();
Thread t = new Thread(r);
t.start();
}
}
Java’s Main Thread
Java starts with one default thread, called the main thread, which runs automatically to execute the
main()method of the program.🔹 Single-Core vs Multi-Core Environment
In a single-core environment, the JVM manages concurrency, switching between threads.
In a multi-core environment, the JVM distributes threads across multiple cores for better performance.
🔹 Thread Life Cycle
In Java, threads officially have five states:
1️⃣ NEW → Thread is created but not started.
2️⃣ RUNNABLE → Thread is ready to run but waiting for CPU execution.
3️⃣ BLOCKED/WAITING → Thread is waiting for some resource or another thread.
4️⃣ TIMED WAITING → Thread is paused for a specific time (sleep(), join(timeout)).
5️⃣ TERMINATED → Thread has completed execution.
🔹 Important Thread Methods
Here are some essential methods used in multithreading:
| Method | Description |
run() | Defines the task to execute inside the thread |
start() | Starts a new thread |
sleep(ms) | Pauses execution for a specific time |
join() | Makes one thread wait for another to finish execution |
setPriority() | Sets priority (MAX, MIN, NORM) |
interrupt() | Interrupts a sleeping/waiting thread |
yield() | Gives CPU time to another thread |
setDaemon(true) | Marks a thread as a daemon thread (background process) |