start() versus run()
30 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)start() and run() look alike but do very different things. start() creates a new thread that runs your task; run() just runs the task on the thread that called it.
run() runs on the calling thread
start() creates a new thread and runs run() on it; calling run() directly just runs the code on the current thread like a normal method.
Calling run() yourself is an ordinary method call. The code runs on the thread that called it, usually main, and no new thread is created.
Example 1 · run() is just a method call
public class RunCallDemo { public static void main(String[] args) { Runnable task = () -> System.out.println("Printing hall ticket on " + Thread.currentThread().getName());
Thread worker = new Thread(task, "printer"); System.out.println("Thread object name: " + worker.getName());
worker.run(); // ordinary call: runs right here, on main worker.run(); // and again, still on main
System.out.println("Was printer ever started? " + worker.isAlive()); }}Thread object name: printer Printing hall ticket on main Printing hall ticket on main Was printer ever started? false
What this code does
- Both calls print
main: the task ran on the calling thread, like any other method. The nameprinterwas never used. isAlive()isfalsebecausestart()was never called; aThreadobject alone is not a running thread. (run()can be called many times, unlikestart().)
The Thread object still exists, with its name and everything, but it is never started. The calling thread simply walks into run(), finishes it and comes back, exactly as with any other method. Several such calls happen one after another, never at the same time.
start() creates a new call stack
start() asks the JVM to create a new thread with its own, empty call stack. That new thread then calls run(). start() itself returns at once: it does not wait for run() to finish.
Example 2 · start() returns at once while the new thread works
public class StartDemo { static void pause(long ms) { try { Thread.sleep(ms); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } }
public static void main(String[] args) throws InterruptedException { Thread worker = new Thread(() -> { pause(200); // the report takes a while System.out.println(Thread.currentThread().getName() + ": report ready"); }, "report-worker");
worker.start(); System.out.println("main: start() returned, worker alive = " + worker.isAlive());
worker.join(); System.out.println("main: after join, worker alive = " + worker.isAlive()); }}main: start() returned, worker alive = true report-worker: report ready main: after join, worker alive = false
What this code does
- The first line comes from
mainstraight afterstart(): it did not wait for the 200 ms report. The worker is still alive because it is busy inrun(). - The middle line is printed by
report-worker, on its own thread. Oncejoin()returns, the worker has finished, soisAlive()isfalse.
Example 3 · A new thread starts with its own call stack
class ResultTask implements Runnable { private final String label;
ResultTask(String label) { this.label = label; }
@Override public void run() { publish(); }
void publish() { // Collect the methods of our own code that are on this thread's call stack. StringBuilder stack = new StringBuilder(); for (StackTraceElement frame : Thread.currentThread().getStackTrace()) { String cls = frame.getClassName(); if (cls.equals("ResultTask") || cls.equals("CallStackDemo")) { stack.append(cls).append('.').append(frame.getMethodName()).append(" <- "); } } System.out.println(label + " on " + Thread.currentThread().getName() + ": " + stack + "(bottom)"); }}
public class CallStackDemo { public static void main(String[] args) throws InterruptedException { Thread t = new Thread(new ResultTask("via start()"), "results"); new ResultTask("via run()").run(); t.start(); t.join(); }}via run() on main: ResultTask.publish <- ResultTask.run <- CallStackDemo.main <- (bottom) via start() on results: ResultTask.publish <- ResultTask.run <- (bottom)
What this code does
getStackTrace()lists the methods the current thread is inside, newest first; the program keeps only our own classes. Called withrun(), the task sits on top ofmain's stack.- Called through
start(),CallStackDemo.mainis not there at all: theresultsthread began with a fresh call stack whose first method of ours isrun().
After start() there are two threads going: the caller carries on with its next line while the new thread works through run(). This is the only way to get real concurrency from a Thread object.
Predict the output
Predict the output
Read each program and pick what it prints. These runs always print the same lines.
Round 1 of 3
The task is run with run(), not start().
run(), but you call start().Calling start() twice and IllegalThreadStateException
A Thread object can be started only once. A second start() on the same object throws IllegalThreadStateException, even when the first run has already finished. A finished thread cannot be restarted.
Example 4 · Starting the same Thread twice
public class StartTwiceDemo { public static void main(String[] args) throws InterruptedException { Runnable sendOtp = () -> System.out.println(Thread.currentThread().getName() + " sent an OTP");
Thread sms = new Thread(sendOtp, "sms-1"); sms.start(); sms.join();
try { sms.start(); // second start on the same object } catch (IllegalThreadStateException e) { System.out.println("Second start failed: " + e); }
Thread retry = new Thread(sendOtp, "sms-2"); // new Thread, same task retry.start(); retry.join(); }}sms-1 sent an OTP Second start failed: java.lang.IllegalThreadStateException sms-2 sent an OTP
What this code does
smshad already finished, but aThreadobject can be started only once, so the secondstart()throwsIllegalThreadStateException(an unchecked exception with no message).- The fix is a new
Threadobject. TheRunnablesendOtpis reused without any change.
To run the same job again, create a new Thread object. The Runnable task itself can be reused: pass the same task object to the new thread.
Proving it with thread names in the output
Printing Thread.currentThread().getName() inside the task is the simplest proof of which thread ran it. If every line says main, the program called run() by mistake and nothing ran in parallel.
Example 5 · The run() bug, found by thread names
public class FindRunBugDemo { public static void main(String[] args) throws InterruptedException { String[] students = {"Asha", "Ravi", "Meena"}; String[] buggy = new String[3]; String[] fixed = new String[3];
Thread[] counters = new Thread[3]; for (int i = 0; i < 3; i++) { int idx = i; counters[i] = new Thread(() -> { buggy[idx] = students[idx] + " served by " + Thread.currentThread().getName(); }, "counter-" + (i + 1)); counters[i].run(); // BUG: should be start() }
Thread[] again = new Thread[3]; for (int i = 0; i < 3; i++) { int idx = i; again[i] = new Thread(() -> { fixed[idx] = students[idx] + " served by " + Thread.currentThread().getName(); }, "counter-" + (i + 1)); again[i].start(); // FIX } for (Thread t : again) { t.join(); }
System.out.println("With run(): " + String.join(" | ", buggy)); System.out.println("With start(): " + String.join(" | ", fixed)); }}With run(): Asha served by main | Ravi served by main | Meena served by main With start(): Asha served by counter-1 | Ravi served by counter-2 | Meena served by counter-3
What this code does
- Both versions give every student a result, so the bug is easy to miss. The names show the truth: with
run()all three were served bymain, one after another. - With
start()each student is served by their own counter thread.mainprints both lines only after joining the started threads.
This bug is easy to miss, because the program still gives correct results. It is only slower, since the tasks run one after another. Name your threads, print the name once while testing, and the mistake shows up at once.
Next step
Check your understanding
12 quick questions