开启多线程启动的世界

一:start()和run()的比较

代码演示

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

        runnable.run();
        new Thread(runnable).start();
    }
}

运行结果

E:\tools\jdk1.8.0_201\bin\java.exe com.example.demo.startthread.StartThread
main
Thread-0

Process finished with exit code 0

main是 runnable.run()执行的结果,Thread-0是 new Thread(runnable).start()执行的结果。你可能会问为什么?别急,继续往下看。

二:start()方法原理解读

start()方法含义

  • 启动新线程:通知JVM在有空闲的情况下就启动新线程
  • 准备工作:首先它会让自己处于就绪状态,就绪状态指我已获取了除cpu以外的其他资源
 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 */
            }
        }
    }

    private native void start0();

通过源码,我们可以大致的看出,start()方法在启动新线程时会首先检查线程状态(这也是为什么不能重复的执行start()方法的原因),加入线程组,最后调用start0()方法。

三: run()方法原理解读

源码

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

可以看出这就是一个普普通通的方法,主线程main直接调用,所以打印出的线程名称是main.

发布了7 篇原创文章 · 获赞 6 · 访问量 131

猜你喜欢

转载自blog.csdn.net/weixin_45319877/article/details/103963723