Java多线程入门案例详解:继承Thread类实现线程

 本文通过一个简单案例,讲解如何通过继承 Thread 类来实现多线程程序,并详细分析了代码结构与运行机制。


一、前言

在 Java 中,实现多线程主要有两种方式:

  • 继承 Thread

  • 实现 Runnable 接口

本文以继承 Thread 类为例,通过一个简单的例子来带大家理解线程的基本创建与启动流程。


二、示例代码

下面是本次讲解的完整代码:

package thread.test;

// 定义一个继承自 Thread 类的 MyThread2 类
class MyThread2 extends Thread {
    // 重写 run() 方法,定义线程执行的任务

    @Override
    public void run() {
        // 无限循环,让线程持续执行
        while (true) {
            // 打印 "hello thread"
            System.out.println("hello thread");
            // 让当前线程休眠 1 秒钟
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                // 处理线程被中断的异常
                throw new RuntimeException(e);
            }

        }
    }
}

public class ThreadDemo2 {
    public static void main(String[] args) {
        // 创建 MyThread2 类的实例
        Thread myThread2=new MyThread2();
        // 调用 start() 方法启动新线程
        myThread2.start();

        // 主线程中的无限循环
        while (true) {
            // 打印 "hello main"
            System.out.println("hello main");
            // 主线程也休眠 1 秒钟
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                // 处理线程被中断的异常
                throw new RuntimeException(e);
            }

        }

    }

}

三、代码详解

1. 定义线程类

通过继承 Thread 类,并重写 run() 方法,定义线程要执行的逻辑。

class MyThread2 extends Thread {
    @Override
    public void run() {
        while (true) {
            System.out.println("hello thread");
            Thread.sleep(1000);
        }
    }
}
  • 通过 new 创建线程对象。

  • 调用 start() 方法来真正启动一个新线程

    • start() 方法内部会调用底层操作系统开辟新线程,并最终执行 run() 方法。

    • 如果直接调用 run(),则只是普通的方法调用,不会开启新线程!


3. 主线程与子线程并发执行

主线程本身也进入一个无限循环:

while (true) {
    System.out.println("hello main");
    Thread.sleep(1000);
}
  • 主线程也每秒打印一次 "hello main"

  • 这样,主线程和子线程各自独立运行,同时输出不同的信息。


四、程序运行结果

运行程序后,控制台将交替输出:

hello main
hello thread
hello thread
hello main
hello main
hello thread
hello main
hello thread
hello main
hello thread
hello main
hello thread
hello main
hello thread
hello main
hello thread
hello main
hello thread
^C

进程已结束,退出代码为 130 (interrupted by signal 2:SIGINT)

但由于线程调度由操作系统控制,因此有时候输出顺序不一定完全规律,比如连续两次出现 "hello thread""hello main" 都是正常的。


五、注意事项

  • 线程安全:本例子中各线程互不干扰。但在实际开发中,如果多个线程操作共享资源,需要考虑线程安全问题。

  • 优雅地处理中断:在捕获 InterruptedException 后,实际项目中建议打断循环优雅退出,而不是简单地抛出异常。

  • 线程销毁:本例代码是无限循环,因此线程不会主动退出,实际开发中应该根据业务逻辑合理控制线程生命周期。


六、总结

通过继承 Thread 类,我们可以快速创建并启动一个新线程,但这种方式有一定局限性,比如:

  • Java 单继承的局限(一个类只能继承一个父类)

  • 扩展性较差

因此,在实际开发中,更推荐实现 Runnable 接口来创建线程,能够让代码更加灵活、解耦。

不过,对于初学者来说,通过继承 Thread 来理解线程基本运行原理是非常重要的一步!

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值