美文网首页
Java start和run两种启动线程方式

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

作者: _灯火阑珊处 | 来源:发表于2020-06-17 13:43 被阅读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 */
                }
            }
        }
    
    • 将该线程加入线程组
    • 启动新线程
    • 处于就绪状态,等待CPU分配资源
    • 获取到CPU分配的资源后,系统会调用thread的run()方法执行线程

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

    run()方法

    源码:

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

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

    相关文章

      网友评论

          本文标题:Java start和run两种启动线程方式

          本文链接:https://www.haomeiwen.com/subject/zljntktx.html