线程的start方法和run方法

在我们分析线程的start方法run方法之前,我们先来看看线程的状态变化:

接下来我们来具体看看线程的start方法和run方法的区别。这里我们通过一个Demo来看看。

public class MyThread extends Thread {
    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName() + " is calling method run...");
        System.out.println("The state of current thread is :" + this.getState().name());
    }
}

public class MyThreadTest {
    public static void main(String[] args) {
        //线程出于新建状态(NEW)
        MyThread myThread = new MyThread();

        //调用run方法,这里其实是主线程发起的调用,run方法就是一个普通的方法
        myThread.run();

        //调用start方法之后,线程才会变为运行的状态(RUNNABLE)
        myThread.start();

        //调用2次start会怎么样?会抛出IllegalThreadStateException异常,只有在线程状态是NEW的时候才能调用start方法,真正运行线程
        //myThread.start();
    }
}

控制台输出:
main is calling method run...
The state of current thread is :NEW
Thread-0 is calling method run...
The state of current thread is :RUNNABLE

为何我们两次调用start方法,第2次会出现异常,分析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 */
            }
        }
    }

猜你喜欢

转载自blog.csdn.net/weixin_39283212/article/details/89554591