java的run方法,Java run()方法如何工作?

本文探讨了Java中多线程的实现方式,通过一个示例代码展示了main方法启动线程后,run方法的执行并不在调用堆栈的顶部。解释了即使main方法没有实现Runnable接口,仍然可以创建和启动线程的原因,并讨论了JVM内部如何启动main线程并执行native方法。
摘要由CSDN通过智能技术生成

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值