线程基础
2026/1/15大约 3 分钟
线程基础
什么是线程
线程是操作系统能够进行运算调度的最小单位,它被包含在进程之中,是进程中的实际运作单位。
进程 vs 线程
| 特性 | 进程 | 线程 |
|---|---|---|
| 资源分配 | 独立的内存空间 | 共享进程的内存空间 |
| 切换开销 | 大 | 小 |
| 通信方式 | IPC(管道、消息队列等) | 直接读写共享变量 |
| 独立性 | 相互独立 | 同一进程内的线程相互影响 |
创建线程的方式
1. 继承 Thread 类
public class MyThread extends Thread {
@Override
public void run() {
System.out.println("线程运行中: " + Thread.currentThread().getName());
}
public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start(); // 启动线程
}
}2. 实现 Runnable 接口(推荐)
public class MyRunnable implements Runnable {
@Override
public void run() {
System.out.println("线程运行中: " + Thread.currentThread().getName());
}
public static void main(String[] args) {
Thread thread = new Thread(new MyRunnable());
thread.start();
// Lambda 写法
new Thread(() -> System.out.println("Lambda 线程")).start();
}
}3. 实现 Callable 接口(有返回值)
public class MyCallable implements Callable<String> {
@Override
public String call() throws Exception {
Thread.sleep(1000);
return "任务执行完成";
}
public static void main(String[] args) throws Exception {
FutureTask<String> futureTask = new FutureTask<>(new MyCallable());
Thread thread = new Thread(futureTask);
thread.start();
// 获取返回值(会阻塞)
String result = futureTask.get();
System.out.println(result);
}
}4. 使用线程池
ExecutorService executor = Executors.newFixedThreadPool(5);
executor.submit(() -> {
System.out.println("线程池中的线程: " + Thread.currentThread().getName());
});
executor.shutdown();线程生命周期
线程状态说明
| 状态 | 说明 |
|---|---|
| NEW | 线程被创建但未启动 |
| RUNNABLE | 可运行状态,等待 CPU 调度 |
| BLOCKED | 阻塞状态,等待获取锁 |
| WAITING | 等待状态,需要其他线程唤醒 |
| TIMED_WAITING | 超时等待,指定时间后自动唤醒 |
| TERMINATED | 终止状态,线程执行完毕 |
线程常用方法
start() vs run()
Thread thread = new Thread(() -> {
System.out.println("当前线程: " + Thread.currentThread().getName());
});
thread.run(); // 在主线程中执行,不会创建新线程
thread.start(); // 创建新线程执行sleep() - 线程休眠
try {
Thread.sleep(1000); // 休眠 1 秒
TimeUnit.SECONDS.sleep(1); // 更优雅的写法
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}join() - 等待线程结束
Thread thread = new Thread(() -> {
try {
Thread.sleep(2000);
System.out.println("子线程执行完毕");
} catch (InterruptedException e) {
e.printStackTrace();
}
});
thread.start();
thread.join(); // 主线程等待子线程执行完毕
System.out.println("主线程继续执行");yield() - 让出 CPU
Thread.yield(); // 提示调度器当前线程愿意让出 CPU,但不保证一定让出interrupt() - 中断线程
Thread thread = new Thread(() -> {
while (!Thread.currentThread().isInterrupted()) {
System.out.println("线程运行中...");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// sleep 被中断会抛出异常,需要重新设置中断标志
Thread.currentThread().interrupt();
break;
}
}
System.out.println("线程被中断,退出");
});
thread.start();
Thread.sleep(3000);
thread.interrupt(); // 中断线程守护线程
守护线程是为其他线程服务的线程,当所有非守护线程结束时,守护线程会自动终止。
Thread daemon = new Thread(() -> {
while (true) {
System.out.println("守护线程运行中...");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
break;
}
}
});
daemon.setDaemon(true); // 必须在 start() 之前设置
daemon.start();
Thread.sleep(3000);
System.out.println("主线程结束,守护线程也会随之结束");线程优先级
Thread thread = new Thread(() -> {});
thread.setPriority(Thread.MAX_PRIORITY); // 10
thread.setPriority(Thread.NORM_PRIORITY); // 5(默认)
thread.setPriority(Thread.MIN_PRIORITY); // 1注意
线程优先级只是给调度器的建议,不保证高优先级线程一定先执行。