All 15 Concurrency & Threads questions
More in Concurrency & Threads
Advertisement
Back to results for “Background Tasks & Hosted Services”
Java › Concurrency & Threads

What is the difference between calling Thread.start() and Thread.run() directly, and why is calling run() directly a common beginner mistake?

Beginner

Answer

start() causes the JVM to allocate a new OS-level thread and asynchronously invoke run() on that new thread of execution; calling run() directly instead simply invokes it as a completely ordinary synchronous method call on the CURRENT thread, with no new thread created at all -- this is a common beginner mistake because the code compiles and appears to run without any error, but the intended concurrent execution silently never actually happens, since run() executes synchronously and blocks the caller just like any normal method call would.
Thread t = new Thread(() -> System.out.println("Running on: " + Thread.currentThread().getName()));

t.start();  // correct: prints a NEW thread name, e.g. "Thread-0", runs concurrently
t.run();    // mistake: prints "main", runs synchronously on the CURRENT thread, no concurrency at all
Real-world example A beginner's attempt to run several tasks "concurrently" by calling run() directly on several Thread objects (instead of start()) is confused when execution is actually happening sequentially, one after another, since each run() call was really just a normal synchronous method invocation on the main thread the whole time.

Common follow-ups: Can you call start() more than once on the same Thread object?;What exception is thrown if you attempt to call start() twice on the same Thread instance?