Java并发(二)--启动线程的正确和错误方式以及原理解析

1. start() 和 run() 方法比较

public class StartThreadTest {
    public static void main(String[] args) {
        Runnable runnable = () -> {
            System.out.println(Thread.currentThread().getName());
        };
        runnable.run();
        new Thread(runnable).start();
    }
}

在这里插入图片描述

直接调用run()方法是由主线程执行,而通过start()方法才是我们创建的线程进行执行的。

2. start() 方法原理解析

2.1 start()方法含义
  1. 启动新线程,通知JVM在有空闲情况下启动新线程。具体启动时间有线程调度器决定。
  2. 准备工作
    • 线程处于就绪状态
  3. 不能重复调用start()方法。
2.2 start() 源码解析
  1. 启动新线程检查线程状态

    首先会判断线程状态,如果线程状态不等于0,就会抛出IllegalThreadStateException(),

    而线程调用start方法后,线程状态就会改变。

  2. 加入线程组

  3. 调用start0()方法

public synchronized void start() {
        
        零状态值对应于状态new
        if (threadStatus != 0)
            throw new IllegalThreadStateException();

       添加线程组
        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 */
            }
        }
    }

3. run() 方法原理解析

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

两种情况:

  • 第一种直接调用,就相当于调用普通方法
  • 第二种,通过start方法来间接调用run(),来执行新线程的任务。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值