搜索
首页Javajava教程如果我们直接调用Java中的run()方法会发生什么?

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

Sep 08, 2023 pm 02:57 PM
java 方法调用run 方法调用函定义

如果我们直接调用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删除

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

AI Hentai Generator

AI Hentai Generator

免费生成ai无尽的。

热工具

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

SecLists

SecLists

SecLists是最终安全测试人员的伙伴。它是一个包含各种类型列表的集合,这些列表在安全评估过程中经常使用,都在一个地方。SecLists通过方便地提供安全测试人员可能需要的所有列表,帮助提高安全测试的效率和生产力。列表类型包括用户名、密码、URL、模糊测试有效载荷、敏感数据模式、Web shell等等。测试人员只需将此存储库拉到新的测试机上,他就可以访问到所需的每种类型的列表。

PhpStorm Mac 版本

PhpStorm Mac 版本

最新(2018.2.1 )专业的PHP集成开发工具

Atom编辑器mac版下载

Atom编辑器mac版下载

最流行的的开源编辑器

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

功能强大的PHP集成开发环境