Core Module
12 min forge
Threads & Runnable
Concurrency basics, lifecycle of a thread, and Thread vs Runnable.
Threads & Runnable
π What is it
Concurrency in Java is the ability of a program to run multiple tasks simultaneously. A Thread is the smallest unit of execution. Java provides two ways to create a thread: extending the Thread class or implementing the Runnable interface.
ποΈ Thread vs Runnable
- Extending
Thread: Simple but limits multiple inheritance. - Implementing
Runnable: Better practice as it allows inheriting from another class and separates the task from the runner.
β‘ Thread Lifecycle
- New: Thread is created but not started.
- Runnable: After
start()is called; ready to run. - Running: Processor has selected it to run.
- Blocked/Waiting: Thread is waiting for a resource or notification.
- Timed Waiting: Waiting for a specific duration (e.g.,
Thread.sleep()). - Terminated: Thread hasn't finished its task.
π» Code example
java Standardclass MyRunnable implements Runnable { public void run() { System.out.println("Thread is running..."); } } public class Main { public static void main(String[] args) { Thread thread = new Thread(new MyRunnable()); thread.start(); // Correct: calls run() in a new thread } }
β Common mistakes
- Calling
run()instead ofstart(): Callingrun()directly executes the method in the CURRENT thread, not a new one. - Race Conditions: Multiple threads accessing shared resources without synchronization.
- Starvation: Higher-priority threads consuming all CPU time, leaving lower-priority threads unable to run.