Thread 的run方法和start方法的区别

start()方法是用来启动线程,实现了多线程运行

点进去查看源码,发现start方法创建一个线程 并让线程处于就绪状态,并且在start方法内会调用start0()方法,而start0作为本地方法 会用c/c++创建一个线程并且调用run方法运行

 


private native void start0();



@Override

public void run() {

    if (target != null) {

        target.run();

    }

}





private void exit() {

    if (group != null) {

        group.threadTerminated(this);

        group = null;

    }



    threadLocals = null;

    inheritableThreadLocals = null;

    inheritedAccessControlContext = null;

    blocker = null;

    uncaughtExceptionHandler = null;

}



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 */

        }

    }

}

而run 方法只是当成普通方法调用,程序还是主线程运行。

注:

Thread 的run方法是运行上一个线程

//而 THread 的start 的方法是创建一个线程并且运行

//尽量实现 runnable 接口 因为有线程池

 

 

posted @ 2019-05-03 20:55  小飞fei  阅读(12)  评论(0)    收藏  举报