So, this question has been answered before (here and here), and the answers totally makes sense to me:
run()
just calls the run()
method of the Thread
object, but without spawning a new thread. So, the code within the run()
method actually is executed on the same thread it was called on.
start()
on the other hands over the the thread instance to the scheduler and calls run()
there, so it spawns a new thread on which the code of the run()
method gets executed.
However, I am struggling to really understand what the meaning of this is, so I developed a case to validate the statements:
public class Test extends Thread{
public void run() {
System.out.println("run() called on thread: " + getName());
}
public static void main(String[] args) throws Exception {
System.out.println("main() called on thread: " + Thread.currentThread().getName());
Test t = new Test();
t.start(); // OR t.run();
}
}
So, if the above was true, the output of the program should be that the name of the threads should be identical if I use t.run()
to execute the print statement, since no new thread should be created and t
is just running on the same thread that it was created on. On the other hand, t.start()
should actually give me two different thread names.
However, in both cases I get the output:
main() called on thread: main
run() called on thread: Thread-0
Can anyone explain why calling t.run()
also spawns a new thread and doesn't actually output:
main() called on thread: main
run() called on thread: main