「ds」Thread线程中start()和run()方法的区别

转载:https://blog.csdn.net/codershamo/article/details/51886430#:~:text=Thread%E7%9A%84run%EF%BC%88%EF%BC%89%E4%B8%8Estart%EF%BC%88%EF%BC%89%E7%9A%84%E5%8C%BA%E5%88%AB&text=%E5%8F%AF%E4%BB%A5%E9%80%9A%E8%BF%87%E5%88%9B%E5%BB%BAThread,%E9%98%BB%E5%A1%9E%E5%92%8C%E6%AD%BB%E4%BA%A1%E3%80%82...

 

1. start()和run()区别


start():用来启动一个线程, 这时此线程是处于就绪状态, 并没有运行。

然后通过此Thread类调用方法run()来完成其运行操作的, 这里方法run()称为线程体, 它包含了要执行的这个线程的内容。

run方法运行结束, 此线程终止, 而CPU再运行其它线程。

start()不能被重复调用。


run(): run()就和普通的成员方法一样,可以被重复调用

单独调用run()的话,会在当前线程中执行run(),而并不会启动新线程!
 

2. 相关源码(JDK1.7)

2.1 start():

public synchronized void start() {
    // 如果线程不是"就绪状态",则抛出异常!
    if (threadStatus != 0)
        throw new IllegalThreadStateException();

    // 将线程添加到ThreadGroup中
    group.add(this);

    boolean started = false;
    try {
        // 通过start0()启动线程
        start0();
        // 设置started标记
        started = true;
    } finally {
        try {
            if (!started) {
                group.threadStartFailed(this);
            }
        } catch (Throwable ignore) {
        }
    }
}

说明:start()实际上通过本地方法start0()调用操作系统的API来创建线程。新的线程处于就绪状态,等待调度器调试执行run()方法。

 

2.2 run():

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

说明:target是一个Runnable对象。run()就是直接调用Thread线程的Runnable成员的run()方法,并不会新建一个线程。

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章