如何区别线程的start方法和run方法

382 阅读1分钟

1. 使用run方法启动线程

  public class ThreadTest {
      private static void attack() {
          System.out.println("Fight");
          System.out.println("Cuurrent Thread is : " + Thread.currentThread().getName());
      }

      public static void main(String[] args) {
          Thread t = new Thread() {
              public void run() {
                  attack();
              }
          };
          System.out.println("Cuurrent main thread is : " + Thread.currentThread().getName());
          t.run();
      }
  }

查看执行结果:

2. 使用start方法启动线程

  public class ThreadTest {
      private static void attack() {
          System.out.println("Fight");
          System.out.println("Cuurrent Thread is : " + Thread.currentThread().getName());
      }
  
      public static void main(String[] args) {
          Thread t = new Thread() {
              public void run() {
                  attack();
              }
          };
          System.out.println("Cuurrent main thread is : " + Thread.currentThread().getName());
          t.start();
      }
  }

查看执行结果:

结果分析

  • 调用run的时候会沿用主线程来执行方法,调用start方法的时候会用子线程执行方法。

  • start方法会调用JVM_StartThread方法去创建一个新的子线程,并通过run方法启动子线程。

调用start()方法会创建一个新的子线程并启动,run()方法只是Thread的一个普通方法的调用,还是在主线程里执行。

有用就拿去,只需要帮忙关注点个小赞,感谢。