zoukankan      html  css  js  c++  java
  • 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()
    方法可以进行多次调用,因为它只是一个普通的方法而已。

  • 相关阅读:
    python字符串
    php设计模式 ---单例模式.
    PHP设计模式---策略模式
    PHP设计模式---适配器模式
    PHP设计模式---抽象工厂模式
    windows下安装redis
    PHP基础知识汇总(四)
    PHP面向对象整理
    PHP基础知识汇总(三)
    PHP基础知识汇总(二)
  • 原文地址:https://www.cnblogs.com/xiaodou00/p/13499597.html
Copyright © 2011-2022 走看看