How does Java run() method work?

后端 未结 4 706
陌清茗
陌清茗 2021-02-15 10:04

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

4条回答
  •  执念已碎
    2021-02-15 10:47

    main method is started in a separate thread by JVM, it is the parent thread of child thread, thats why you dont see child thread at the top of invocation hierarchy.

    So in your case JVM created a thread started your program, which also extends Thread.

    Then in your main method you created a new instance of your class, called start on it, this will start a new thread which is child of thread started by JVM to launch your program.

    Since main method is a starting point for a standalone java program, it is the responsiblity of JVM to launch it in a separate thread, you dont write code for it.

    While launching a program by calling main method JVM doesn't need it to be a Thread or implement Runnable, it is a standard procedure.

    Description from Inside Java Virtual Machine

    The main() method of an application's initial class serves as the starting point for that application's initial thread. The initial thread can in turn fire off other threads.

    Inside the Java virtual machine, threads come in two flavors: daemon and non- daemon. A daemon thread is ordinarily a thread used by the virtual machine itself, such as a thread that performs garbage collection. The application, however, can mark any threads it creates as daemon threads. The initial thread of an application--the one that begins at main()--is a non- daemon thread.

    A Java application continues to execute (the virtual machine instance continues to live) as long as any non-daemon threads are still running. When all non-daemon threads of a Java application terminate, the virtual machine instance will exit. If permitted by the security manager, the application can also cause its own demise by invoking the exit() method of class Runtime or System.

    The call hierarchy is not governed by you it is governed by the underlying thread scheduler.

    So for example If I run the same code on my machine this is the output

    Exception in thread "main" java.lang.RuntimeException: Exception from main thread
        at TestThread.main(TestThread.java:6)
    Exception in thread "Thread-1" java.lang.RuntimeException: Exception from child thread
        at TestThread.run(TestThread.java:9)
        at java.lang.Thread.run(Thread.java:662)
    

    so when you ran your example, scheduler choose to let go child thread first before main.

    Adding to @JB Nizet, how a program will be invoked, or how a thread lifecycle will be implemented depends from underlying OS and hardware, which will and does vary.

    No single implementation details would provide a complete answer, each implementation will vary.

提交回复
热议问题