Video in progress
What happens if you call run() instead of start() on a Thread?
Thread t = new Thread(() ->
System.out.println(Thread.currentThread().getName()));
t.run();
t.start();
run() executes as an ordinary method on the current thread, and no new thread is created. A new thread appears only when start() is called, and it calls run() on its own.
📖 Answer
The output:
main
Thread-0
t.run() is just a call to the Runnable's method. The code runs sequentially on the main thread, with no parallelism at all. t.start() tells the JVM "create a new native thread and run run() on it".
Another trap: you can't call start() twice on the same object. Even after the thread has finished, calling start() again throws an IllegalThreadStateException. If you need to run the task again, create a new Thread or submit it to an executor again.
In interviews this question often comes in the form "is this code running in parallel?". Printing the thread name is the quickest way to check.
Sign up to mark studied questions and save your progress.