java线程启动原理

java线程启动原理

start方法和run方法的比较

public class startAndRunMedthod {

    public static void main(String[] args) {

        Runnable runnable = () -> {
            System.out.println(Thread.currentThread().getName());
        };
        runnable.run();

        new Thread(runnable).start();

    }

}
  • 输出结果
main
Thread-0

    //  main 是由run方法输出的
    //  Thread-0是由start方法输出的

start方法的原理

start方法的含义
  • 启动新线程
调用start方法只是告诉JVM要启动新线程,具体启动的数据要根据任务调度来决定
调用start的方法需要两个线程来同时运行,因为需要另外一个线程来执行这个start方法
  • 准备工作
调用start方法之后,先让自己处于就绪状态(已经取到了除CPU以外的其他资源,设置了上下文,栈,线程状态,PC等)
然后被CPU调度到执行状态之后,等待CPU资源,然后才处于运行状态,执行run方法里面的代码
  • 不能重复执行start方法
public class startTwice {

    public static void main(String[] args) {
        Thread thread = new Thread();
        thread.start();
        thread.start();
    }
}

运行结果

Exception in thread "main" java.lang.IllegalThreadStateException
	at java.lang.Thread.start(Thread.java:708)
	at com.jx.JavaTest.satrtThread.startTwice.main(startTwice.java:8)

执行start方法之后,线程就从new状态转变成后续的状态,执行完毕,线程就会变成终止状态。

在start的源码中,启动新线程先检查线程状态,然后将线程加入线程组,调用start0方法

  • 源码(请看注释)
private volatile int threadStatus = 0;

public synchronized void start() {
    
    // 调用start方法,首先先检查状态参数,这个参数由最上面可见,初始值就为0,表示没有启动
    if (threadStatus != 0)
        throw new IllegalThreadStateException();
	
    // 加入到线程组
    group.add(this);

    boolean started = false;
    
    // 执行start0方法
    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 */
        }
    }
}

private native void start0();

run方法的原理

  • 源码
@Override
public void run() {
    if (target != null) {
        target.run();
    }
}

run方法就是一个普通方法,和自己写的方法没有区别

要想真正的启动线程,不能去执行run方法,而是要去执行start方法,间接执行run方法

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

健鑫.

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值