Java start和run两种启动线程方式

2020-06-17  本文已影响0人  _灯火阑珊处

start方法和run方法启动线程

public class StartAndRunMethod {

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

        new Thread(runnable).start();
    }

}

start()方法源码:

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();
            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 */
            }
        }
    }

多个线程,调用start()方法的顺序,并不是真正执行线程的顺序。

run()方法

源码:

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

启动线程要调用start()方法,间接的去调用run()方法

上一篇下一篇

猜你喜欢

热点阅读