start() 和 run() 的区别

1.start()源码

首先从 Thread 源码来看,start() 方法属于 Thread 自身的方法,并且使用了
synchronized 来保证线程安全,源码如下:

public synchronized void start() {

    // 状态验证,不等于 NEW 的状态会抛出异常

    if (threadStatus != 0)

        throw new IllegalThreadStateException();

    // 通知线程组,此线程即将启动

    group.add(this);

    boolean started = false;

    try {

        start0();

        started = true;

    } finally {

        try {

            if (!started) {

                group.threadStartFailed(this);

            }

        } catch (Throwable ignore) {

            // 不处理任何异常,如果 start0 抛出异常,则它将被传递到调用堆栈上

        }

    }

}

2.run()源码

run() 方法为 Runnable 的抽象方法,必须由调用类重写此方法,重写的 run()
方法其实就是此线程要执行的业务方法,源码如下:

public class Thread implements Runnable {

 // 忽略其他方法......

  private Runnable target;

  \@Override

  public void run() {

      if (target != null) {

          target.run();

      }

  }

}

\@FunctionalInterface

public interface Runnable {

    public abstract void run();

}

从执行的效果来说,start() 方法可以开启多线程,让线程从 NEW 状态转换成 RUNNABLE
状态,而 run() 方法只是一个普通的方法。
其次,它们可调用的次数不同,start() 方法不能被多次调用,否则会抛出
java.lang.IllegalStateException;而 run()
方法可以进行多次调用,因为它只是一个普通的方法而已。

posted @ 2020-08-13 23:09  0小豆0  阅读(596)  评论(0编辑  收藏  举报
隐藏
对话
对话