多线程start()与run()的区别

概要


1.start()与run()介绍

2.start()与run()源码查看

3.start()与run()测试

start()与run()介绍

1.通过我们在启动线程的时候使用的start,为什么不用run呢? 因为start()会新开一个线程来执行;而run只是一个普通想法,相当于当前线程来调用,不会启动新线程;

2.start()只能调用一次,run()可以调用多次

start()与run()源码查看

1.先来看下start()的源码,start()启动线程其实是通过start0()启动的

public synchronized void start() {
        /**
         * This method is not invoked for the main method thread or "system"
         * group threads created/set up by the VM. Any new functionality added
         * to this method in the future may have to also be added to the VM.
         *
         * A zero status value corresponds to state "NEW".
         */
        if (threadStatus != 0)
            throw new IllegalThreadStateException();

        /* Notify the group that this thread is about to be started
         * so that it can be added to the group's list of threads
         * and the group's unstarted count can be decremented. */
        group.add(this);  //添加到线程组

        boolean started = false;
        try {
            start0();  //调用本地方法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(); //本地方法start0()

2.run()源码

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

只是调用了runnable里面的run方法,并没有创建新的线程

start()与run()测试

理论也看了,源码也看了,线程来实践一下是不是这样的

public class StartRun {

    public static void main(String[] args){

        Thread test=new Thread(new Runnable() {
            @Override
            public void run() {

                System.out.println(Thread.currentThread().getName());
            }
        });
        test.run();

    }
}
对应的输出结果为main,即主线程,并没有创建新的线程
public class StartRun {

    public static void main(String[] args){

        Thread test=new Thread(new Runnable() {
            @Override
            public void run() {

                System.out.println(Thread.currentThread().getName());
            }
        });
        test.start();

    }
}

对应的输出结果为Thread-0,创建了新的线程
原文地址:https://www.cnblogs.com/dpains/p/7488770.html