Multi-threading in Java is done by defining run() and invoking start().
Start delegates to a native method that launches a thread through operating system routines and run() is invoked from within this newly spawned thread.
When a standalone application is started a main thread is automatically created to execute the main().
Now consider this code -
public class Test extends Thread {
public static void main(String[] args) throws Exception {
new Thread(new Test()).start();
throw new RuntimeException("Exception from main thread");
}
public void run() {
throw new RuntimeException("Exception from child thread");
}
}
This is the output -
java.lang.RuntimeException: Exception from child thread
at com.Test.run(Test.java:11)
at java.lang.Thread.run(Thread.java:662)
java.lang.RuntimeException: Exception from main thread
at com.Test.main(Test.java:8)
If main() method is launched via a thread why doesn't run() show up at the top of invocation hierarchy?
How could the main thread get spawned without implementing Runnable?
解决方案
I haven't looked at the internals of the JVM, but I would guess that the JVM instantiates the main thread to run the main method, but runs this main thread by invoking native code directly, without going through the classical Java classes and methods to start the thread.