Card 03/ 08
All 8 cards
GotchaDifficulty: Intermediate1 min
Why Calling run() Directly Started Nothing
A program that creates four threads and runs no faster than it did. The work is definitely happening — the logs prove it — and it is all happening on one thread.
Thread worker = new Thread(() -> {
System.out.println("on " + Thread.currentThread().getName());
});
worker.run();
worker.start();on main
on Thread-0run() is an ordinary method. Calling it calls it, on whatever thread you are already on, exactly as calling any other method would. Nothing about a Thread object makes its methods special.
start() is the one that asks the virtual machine for a new thread and has that thread call run(). It is the only line in Java that creates one.
Print Thread.currentThread().getName() when you are not sure. If everything says main, nothing is running concurrently, whatever the code looks like.