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

  1. New: Thread is created but not started.
  2. Runnable: After start() is called; ready to run.
  3. Running: Processor has selected it to run.
  4. Blocked/Waiting: Thread is waiting for a resource or notification.
  5. Timed Waiting: Waiting for a specific duration (e.g., Thread.sleep()).
  6. Terminated: Thread hasn't finished its task.

πŸ’» Code example

java Standard
class 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 of start(): Calling run() 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.