java 线程 run_Java线程Run和Start的区别

本文详细探讨了Java中Thread的start()和run()方法的区别。通过代码示例展示start()会启动新线程并调用run(),而直接调用run()方法则不会创建新线程,而是同步执行。分析了源码,揭示了start()方法内部调用native方法启动线程,并在新线程中执行run()的过程。
摘要由CSDN通过智能技术生成

先上结论:run只是Thread里面的一个普通方法,start是启动线程的方法。何以见得呢?可以执行下面的代码看看run和start的区别:

packagecom.basic.thread;/***@authorzhangxingrui

* @create 2019-02-16 20:12

**/

public classTestRunAndStart {private static voidsayHello(){

System.out.println("hello, world");

}public static voidmain(String[] args) {

Thread thread= new Thread(newRunnable() {

@Overridepublic voidrun() {

sayHello();

System.out.println("Current thread: " +Thread.currentThread().getName());

}

});

thread.run();

thread.start();

}

}

执行结果:

5cbabe0a89023b82bf7aa7387b456895.png

由此可以看到子线程是由start来启动的,里面调用了run,所以打印出来的是子线程的name。

另外也可以从start方法的底层代码看到,首先进入start方法里面

public synchronized voidstart() {/*** This method is not invoked for the main method thread or "system"

* group threads created/set up by the VM. Any new functionality added

* to this method in the future may have to also be added to the VM.

*

* A zero status value corresponds to state "NEW".*/

if (threadStatus != 0)throw newIllegalThreadStateException();/*Notify the group that this thread is about to be started

* so that it can be added to the group's list of threads

* and the group's unstarted count can be decremented.*/group.add(this);boolean started = false;try{

start0();

started= true;

}finally{try{if (!started) {

group.threadStartFailed(this);

}

}catch(Throwable ignore) {/*do nothing. If start0 threw a Throwable then

it will be passed up the call stack*/}

}

}

里面调用了start0,继续跟进

private native void start0();

哦,这里就调了native方法了,再往下我们就看不到了。但是可以去openjdk的源码里面去看一下,我用的是jdk8。

去openjdk看源码

1dd73636337810e3c7338101c1c4881c.png

这里调用了JVM_StartThread,在jvm.h里面

继续进入

8f83217ddea2a837a3cc89688936add1.png

重点看最下面的语句native_thread = new JavaThread(&thread_entry, sz),好,new JavaThread的时候传入了thread_entry,我们再去

看一下啊thread_entry是什么:

55dabbb9208e5e96af456f5d8c2255d1.png

在thread_entry这个函数里面调用call_virtual方法,重点是它传入的参数run_method_name,从这里我们就知道了,噢,

原来start最终会在新线程里面调用run方法。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值