本文通过一个简单案例,讲解如何通过继承
Thread
类来实现多线程程序,并详细分析了代码结构与运行机制。
一、前言
在 Java 中,实现多线程主要有两种方式:
-
继承
Thread
类 -
实现
Runnable
接口
本文以继承 Thread
类为例,通过一个简单的例子来带大家理解线程的基本创建与启动流程。
二、示例代码
下面是本次讲解的完整代码:
package thread.test;// 定义一个继承自 Thread 类的 MyThread2 类
class MyThread2 extends Thread {// 重写 run() 方法,定义线程执行的任务@Overridepublic 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 {@Overridepublic 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
来理解线程基本运行原理是非常重要的一步!