直接调用 Java 线程的 run() 方法会发生什么?

前言

  • 在Java中,多线程编程是一个重要的概念,尤其是在处理并发任务时。线程是Java中实现多线程的一种方式。在使用线程时,理解 run() 方法和 start() 方法之间的区别是至关重要的。本文将深入探讨如果直接调用线程的 run() 方法会发生什么。
  • 先说结论:直接调用 run() 方法不会启动一个新的线程,它只是普通方法调用,代码在当前线程中同步顺序执行。

回顾

  • Java 提供了继承 Thread 类、实现Runnable接口两种方式来实现线程,无论使用哪种方式,都需要重写 run() 方法,这是线程执行的入口点。启动一个线程通常使用 Thread 对象的 start() 方法,该方法会触发线程的启动,并最终调 用run() 方法。

run() 方法 vs start() 方法

run()方法

  • run()方法包含了线程要执行的代码。
  • 直接调用run()方法不会启动一个新线程,它只是在当前线程中执行run()方法体中的代码。
  • 换句话说,直接调用run()方法相当于调用一个普通的方法,没有并发行为。

start()方法

整理了一份面试笔记包括了:Java面试、Spring、JVM、MyBatis、Redis、MySQL、并发编程、微服务、Linux、Springboot、SpringCloud、MQ、Kafka 面试专题

需要全套面试笔记的【点击此处即可】即可免费获取

  • start()方法会创建一个新的线程,并在新的线程中执行run()方法。
  • 调用start()方法会使线程从“新建”状态变为“就绪”状态,等待CPU调度。

直接调用 run() 方法的影响

  • 为了更好地理解直接调用 run() 方法的影响,考虑以下示例代码:
 

Java

复制代码

class MyThread extends Thread { public void run() { System.out.println("Thread is running"); } } public class Main { public static void main(String[] args) { MyThread thread = new MyThread(); // 直接调用run()方法 thread.run(); // 调用start()方法 thread.start(); } }

  • 在上述代码中,thread.run() 和 thread.start() 的行为是完全不同的。

直接调用 run() 方法

  • 当thread.run()被调用时,输出“Thread is running”。这段代码在主线程中执行,没有启动新的线程。此时,主线程和线程对象的run()方法体是同步顺序执行的。

调用 start() 方法

  • 当thread.start()被调用时,输出“Thread is running”。这段代码在一个新线程中执行,与主线程并发运行。主线程和新启动的线程是同时执行的,体现了多线程的并发特性。

示例解析

  • 通过以下代码示例可以更清晰地看出区别:
 

Java

复制代码

class MyRunnable implements Runnable { public void run() { for (int i = 0; i < 5; i++) { System.out.println("Runnable running " + i); } } } public class Main { public static void main(String[] args) { MyRunnable myRunnable = new MyRunnable(); Thread thread = new Thread(myRunnable); // 直接调用run()方法 myRunnable.run(); // 调用start()方法 thread.start(); } } // 输出 Runnable running 0 Runnable running 1 Runnable running 2 Runnable running 3 Runnable running 4 Runnable running 0 Runnable running 1 Runnable running 2 Runnable running 3 Runnable running 4

  • 前五行输出是 myRunnable.run() 直接调用产生的,后五行是 thread.start() 启动的新线程产生的。

结论

  • 直接调用 run() 方法不会启动一个新的线程,它只是普通方法调用,代码在当前线程中同步顺序执行。而调用 start() 方法则会启动一个新的线程,并在该线程中执行 run() 方法的代码。

个人简介

👋 你好,我是 Lorin 洛林,一位 Java 后端技术开发者!座右铭:Technology has the power to make the world a better place.

🚀 我对技术的热情是我不断学习和分享的动力。我的博客是一个关于Java生态系统、后端开发和最新技术趋势的地方。

🧠 作为一个 Java 后端技术爱好者,我不仅热衷于探索语言的新特性和技术的深度,还热衷于分享我的见解和最佳实践。我相信知识的分享和社区合作可以帮助我们共同成长。

💡 在我的博客上,你将找到关于Java核心概念、JVM 底层技术、常用框架如Spring和Mybatis 、MySQL等数据库管理、RabbitMQ、Rocketmq等消息中间件、性能优化等内容的深入文章。我也将分享一些编程技巧和解决问题的方法,以帮助你更好地掌握Java编程。

🌐 我鼓励互动和建立社区,因此请留下你的问题、建议或主题请求,让我知道你感兴趣的内容。此外,我将分享最新的互联网和技术资讯,以确保你与技术世界的最新发展保持联系。我期待与你一起在技术之路上前进,一起探讨技术世界的无限可能性。

  • 6
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值