Memra

Threads & Runnable

Creating threads, the start() vs run() trap, thread lifecycle, join and sleep.

What is a thread?

A thread is an independent unit of execution inside the JVM. Multiple threads share the same heap memory but each has its own call stack. You create one by giving it a Runnable — a task to run:

Runnable task = () -> System.out.println("running on: " + Thread.currentThread().getName());
Thread t = new Thread(task);
t.start();  // schedules the thread — returns immediately

The alternative — subclassing Thread — is almost never the right approach in new code:

// Anti-pattern — prefer Runnable or Callable
class MyThread extends Thread {
    public void run() { System.out.println("running"); }
}
new MyThread().start();

Prefer Runnable because your task class can still extend another class, and the logic is decoupled from thread-management concerns.

start() vs run() — the most important thread trap:

t.run();   // calls run() on the CURRENT thread — no new thread is started
t.start(); // schedules the task on a NEW thread

Thread lifecycle states: NEW → RUNNABLE → (BLOCKED / WAITING / TIMED_WAITING) → TERMINATED.

join and sleep:

t.start();
t.join();    // current thread waits until t has finished
Thread.sleep(500);  // static — pauses the CURRENT thread 500 ms; throws InterruptedException
NORMAL ~/memra/learn/java-from-zero/threads-and-runnable utf-8 LF