线程基础与生命周期
创建线程的方式
1. 继承 Thread 类
java
/**
* 继承 Thread 类
* @author yjhu
*/
public class MyThread extends Thread {
@Override
public void run() {
System.out.println("Thread running: " + Thread.currentThread().getName());
}
}
// 使用
MyThread thread = new MyThread();
thread.start();2. 实现 Runnable 接口(推荐)
java
/**
* 实现 Runnable 接口
* @author yjhu
*/
public class MyRunnable implements Runnable {
@Override
public void run() {
System.out.println("Runnable running: " + Thread.currentThread().getName());
}
}
// 使用
Thread thread = new Thread(new MyRunnable());
thread.start();
// Lambda 简化
Thread thread2 = new Thread(() -> {
System.out.println("Lambda Runnable");
});
thread2.start();3. 实现 Callable 接口(有返回值)
java
/**
* 实现 Callable 接口
* @author yjhu
*/
public class MyCallable implements Callable<String> {
@Override
public String call() throws Exception {
Thread.sleep(1000);
return "Callable result";
}
}
// 使用
FutureTask<String> futureTask = new FutureTask<>(new MyCallable());
Thread thread = new Thread(futureTask);
thread.start();
// 获取返回值(阻塞)
String result = futureTask.get();4. 线程池(生产环境推荐)
java
ExecutorService executor = Executors.newFixedThreadPool(10);
executor.submit(() -> {
System.out.println("Thread pool task");
});
executor.shutdown();线程的生命周期
┌───────────────────────────────────────────────────────────────┐
│ │
│ ┌───────┐ start() ┌─────────┐ │
│ │ NEW │ ────────────→ │ RUNNABLE│ │
│ └───────┘ └────┬────┘ │
│ │ │
│ ┌───────────────────────┼───────────────────────┐ │
│ ↓ ↓ ↓ │
│ ┌────────────┐ ┌────────────┐ ┌──────────┐ │
│ │ BLOCKED │ │ WAITING │ │ TIMED_ │ │
│ │ (等待锁) │ │ (无限等待) │ │ WAITING │ │
│ └─────┬──────┘ └─────┬──────┘ └────┬─────┘ │
│ │ │ │ │
│ └──────────────────────┴──────────────────────┘ │
│ │ │
│ ↓ │
│ ┌────────────┐ │
│ │ TERMINATED │ │
│ └────────────┘ │
└───────────────────────────────────────────────────────────────┘状态说明
| 状态 | 描述 | 触发方式 |
|---|---|---|
| NEW | 新建,尚未启动 | new Thread() |
| RUNNABLE | 可运行(包含 Ready 和 Running) | start() |
| BLOCKED | 阻塞,等待获取锁 | 等待 synchronized |
| WAITING | 无限期等待 | wait(), join(), park() |
| TIMED_WAITING | 限时等待 | sleep(n), wait(n), join(n) |
| TERMINATED | 终止 | run() 执行完毕 |
状态转换示例
java
/**
* 线程状态转换演示
* @author yjhu
*/
public class ThreadStateDemo {
public static void main(String[] args) throws InterruptedException {
Thread thread = new Thread(() -> {
try {
// RUNNABLE → TIMED_WAITING
Thread.sleep(1000);
// 同步块内等待
synchronized (ThreadStateDemo.class) {
// RUNNABLE → WAITING
ThreadStateDemo.class.wait();
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
});
System.out.println("创建后: " + thread.getState()); // NEW
thread.start();
System.out.println("启动后: " + thread.getState()); // RUNNABLE
Thread.sleep(100);
System.out.println("sleep中: " + thread.getState()); // TIMED_WAITING
Thread.sleep(1500);
System.out.println("wait中: " + thread.getState()); // WAITING
}
}常用方法
sleep vs wait
| 方法 | 所属类 | 释放锁 | 唤醒方式 |
|---|---|---|---|
sleep(ms) | Thread | ❌ 不释放 | 时间到自动唤醒 |
wait() | Object | ✅ 释放 | notify() / notifyAll() |
join
等待另一个线程执行完毕。
java
Thread t1 = new Thread(() -> {
try {
Thread.sleep(2000);
System.out.println("t1 完成");
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
});
t1.start();
t1.join(); // 主线程阻塞,等待 t1 执行完毕
System.out.println("主线程继续");interrupt
中断线程,设置中断标志位。
java
Thread t = new Thread(() -> {
while (!Thread.currentThread().isInterrupted()) {
// 工作...
}
System.out.println("线程被中断,退出");
});
t.start();
Thread.sleep(1000);
t.interrupt(); // 请求中断线程优先级
java
thread.setPriority(Thread.MAX_PRIORITY); // 10
thread.setPriority(Thread.NORM_PRIORITY); // 5(默认)
thread.setPriority(Thread.MIN_PRIORITY); // 1注意:优先级只是建议,不保证执行顺序。
守护线程
java
Thread daemon = new Thread(() -> {
while (true) {
// 后台任务...
}
});
daemon.setDaemon(true); // 设置为守护线程
daemon.start();特点:当所有用户线程结束时,守护线程会自动终止。 应用:GC 线程、心跳检测等。
