多线程基础:线程创建、启动与生命周期管理
多线程是现代编程中提高程序性能的重要手段。本文将介绍多线程的基础知识,包括线程的创建与启动方式,以及线程生命周期的管理,并通过Java代码示例进行说明。
线程的创建与启动方式
在Java中,创建线程主要有两种方式:
1. 继承Thread类
class MyThread extends Thread {@Overridepublic void run() {System.out.println("线程运行中: " + this.getName());}
}public class ThreadDemo {public static void main(String[] args) {MyThread thread = new MyThread();thread.start(); // 启动线程}
}
2. 实现Runnable接口
class MyRunnable implements Runnable {@Overridepublic void run() {System.out.println("线程运行中: " + Thread.currentThread().getName());}
}public class RunnableDemo {public static void main(String[] args) {Thread thread = new Thread(new MyRunnable());thread.start(); // 启动线程}
}
其中比较推荐使用实现Runnable接口的方式,因为Java不支持多重继承,实现接口的方式更加灵活。
线程生命周期管理
Java线程有以下几种状态:
- NEW(新建):线程被创建但尚未启动
- RUNNABLE(可运行):线程正在JVM中执行或等待操作系统资源
- BLOCKED(阻塞):线程等待监视器锁
- WAITING(等待):线程无限期等待其他线程执行特定操作
- TIMED_WAITING(计时等待):线程在指定时间内等待
- TERMINATED(终止):线程已完成执行
线程状态转换示例
public class ThreadLifecycleDemo {public static void main(String[] args) throws InterruptedException {// NEW状态Thread thread = new Thread(() -> {try {// TIMED_WAITING状态Thread.sleep(1000);synchronized (ThreadLifecycleDemo.class) {// 获取锁后执行System.out.println("线程获取到锁");}} catch (InterruptedException e) {e.printStackTrace();}});System.out.println("创建后状态: " + thread.getState()); // NEWthread.start();System.out.println("启动后状态: " + thread.getState()); // RUNNABLE// 主线程休眠500ms,确保子线程进入TIMED_WAITINGThread.sleep(500);System.out.println("休眠中状态: " + thread.getState()); // TIMED_WAITING// 主线程获取锁,使子线程进入BLOCKEDsynchronized (ThreadLifecycleDemo.class) {Thread.sleep(1500);System.out.println("等待锁时状态: " + thread.getState()); // BLOCKED}// 等待线程结束thread.join();System.out.println("结束后状态: " + thread.getState()); // TERMINATED}
}
线程基本操作
1. 线程休眠
try {Thread.sleep(1000); // 休眠1秒
} catch (InterruptedException e) {e.printStackTrace();
}
2. 线程加入(等待线程完成)
Thread thread = new Thread(() -> {System.out.println("子线程执行");
});
thread.start();
thread.join(); // 主线程等待子线程执行完毕
System.out.println("主线程继续执行");
3. 线程中断
Thread thread = new Thread(() -> {while (!Thread.currentThread().isInterrupted()) {System.out.println("线程运行中");try {Thread.sleep(1000);} catch (InterruptedException e) {// 捕获中断异常后中断状态会被清除System.out.println("线程被中断");Thread.currentThread().interrupt(); // 重新设置中断状态}}
});thread.start();
Thread.sleep(3000);
thread.interrupt(); // 中断线程
总结
多线程编程是提高程序性能的有效手段,但也带来了复杂性。理解线程的创建方式、生命周期和基本操作是掌握多线程编程的基础。在实际开发中,还需要注意线程安全问题,合理使用同步机制。后续可以进一步学习线程池、并发工具类等高级主题。