源码角度分析:线程的start和run方法的区别

start()方法会启动一个新的线程并执行,而run()方法只是类的一个普通方法,不会创建新的线程

代码演示

调用run()时:

public static void main(String[] args) throws InterruptedException {
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("current thread is : " + Thread.currentThread().getName());
            }
        });
        thread.run();
    }

控制台: (打印的当前线程仍为主线程)

current thread is : main

调用start()

public static void main(String[] args) throws InterruptedException {
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("current thread is : " + Thread.currentThread().getName());
            }
        });
        thread.start();
    }

控制台:(打印的当前线程为 新的子线程)

current thread is : Thread-0 

 

源码追踪

start()方法

public synchronized void start() {

    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 */
        }
    }
}
private native void start0();

start()内部调用的start0()为native方法,需要追踪JVM底层源码

https://hg.openjdk.java.net/jdk8u

Thread类在包java.lang下,故依次打开以下目录 

browse -   src / share / native /  java / lang 

https://hg.openjdk.java.net/jdk8u/jdk8u/jdk/file/f9ea6cf9425f/src/share/native/java/lang 

 

 

 start0方法,调用的是 JVM_StartThread、

进一步进入Hotspot源码 jdk8u/jdk8u/hotspot: e2ac513ec7b3 src/share/vm/prims/jvm.cpp

 最终会创建一个新的线程并执行

run()方法

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

直接执行了  内部类run方法(Runnable的实现类),没有任何特殊操作;

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值