如果我们直接调用Java中的run()方法会发生什么?

PHPz
PHPz 转载
2023-09-08 14:57:02 912浏览

如果我们直接调用Java中的run()方法会发生什么?

直接调用 Thread 对象的 run() 方法不会启动单独的线程,并且可以在当前线程内执行。要从单独的线程中执行 Runnable.run,请执行以下操作之一

  • 使用 Runnable 构造一个线程> 对象并调用 Thread 上的 start() 方法。
  • 定义 Thread 对象的子类并覆盖其 run() 方法的定义。然后构造该子类的实例并直接调用该实例的 start() 方法。

示例

public class ThreadRunMethodTest {
   public static void main(String args[]) {
      MyThread runnable = new MyThread();
      runnable.run(); // Call to run() method does not start a separate thread
      System.out.println("Main Thread");
   }
}
class MyThread extends Thread {
   public void run() {
      try {
         Thread.sleep(1000);
      } catch (InterruptedException e) {
         System.out.println("Child Thread interrupted.");
      }
      System.out.println("Child Thread");
   }
}

在上面的示例中,主线程 ThreadRunMethodTest 使用 run() 方法调用子线程 MyThread。这会导致子线程在主线程的其余部分执行之前运行完成,以便在“Main Thread”之前打印“Child Thread”。

输出

Child Thread
Main Thread

以上就是如果我们直接调用Java中的run()方法会发生什么?的详细内容,更多请关注php中文网其它相关文章!

声明:本文转载于:tutorialspoint,如有侵犯,请联系admin@php.cn删除