Java线程基础 #

一、线程概述 #

1.1 进程与线程 #

  • 进程:正在运行的程序,是资源分配的基本单位
  • 线程:进程中的执行单元,是CPU调度的基本单位

1.2 多线程优势 #

  • 提高CPU利用率
  • 提高程序响应速度
  • 简化异步事件处理

二、线程创建 #

2.1 继承Thread类 #

java
public class MyThread extends Thread {
    @Override
    public void run() {
        for (int i = 0; i < 5; i++) {
            System.out.println(Thread.currentThread().getName() + ": " + i);
        }
    }
}

// 使用
MyThread thread = new MyThread();
thread.start();

2.2 实现Runnable接口 #

java
public class MyRunnable implements Runnable {
    @Override
    public void run() {
        for (int i = 0; i < 5; i++) {
            System.out.println(Thread.currentThread().getName() + ": " + i);
        }
    }
}

// 使用
Thread thread = new Thread(new MyRunnable());
thread.start();

// 使用Lambda
Thread thread2 = new Thread(() -> {
    System.out.println("Lambda线程");
});
thread2.start();

2.3 实现Callable接口 #

java
public class MyCallable implements Callable<Integer> {
    @Override
    public Integer call() throws Exception {
        int sum = 0;
        for (int i = 1; i <= 100; i++) {
            sum += i;
        }
        return sum;
    }
}

// 使用
FutureTask<Integer> task = new FutureTask<>(new MyCallable());
Thread thread = new Thread(task);
thread.start();

try {
    Integer result = task.get();  // 获取返回值
    System.out.println("结果: " + result);
} catch (Exception e) {
    e.printStackTrace();
}

2.4 三种方式对比 #

方式 优点 缺点
继承Thread 简单 不能继承其他类
实现Runnable 灵活,可继承其他类 无返回值
实现Callable 有返回值,可抛异常 使用复杂

三、线程生命周期 #

3.1 线程状态 #

text
NEW(新建)
    ↓ start()
RUNNABLE(可运行)
    ↓ 获取CPU
RUNNING(运行中)
    ↓ sleep/wait/block
BLOCKED/WAITING/TIMED_WAITING(阻塞)
    ↓ 唤醒
RUNNABLE
    ↓ run()结束
TERMINATED(终止)

3.2 状态转换 #

java
Thread thread = new Thread(() -> {});  // NEW
thread.start();                         // RUNNABLE
thread.sleep(1000);                     // TIMED_WAITING
thread.wait();                          // WAITING
thread.notify();                        // RUNNABLE
// run()执行完毕                          // TERMINATED

四、线程常用方法 #

4.1 基本方法 #

java
Thread thread = Thread.currentThread();

// 获取信息
thread.getName();       // 线程名
thread.getId();         // 线程ID
thread.getPriority();   // 优先级
thread.getState();      // 状态
thread.isAlive();       // 是否存活
thread.isDaemon();      // 是否守护线程

// 设置信息
thread.setName("MyThread");
thread.setPriority(Thread.MAX_PRIORITY);  // 1-10
thread.setDaemon(true);  // 设置为守护线程

4.2 sleep休眠 #

java
try {
    Thread.sleep(1000);  // 休眠1秒
} catch (InterruptedException e) {
    e.printStackTrace();
}

4.3 yield让出CPU #

java
Thread.yield();  // 让出CPU,进入就绪状态

4.4 join等待线程结束 #

java
Thread t = new Thread(() -> {
    for (int i = 0; i < 5; i++) {
        System.out.println("子线程: " + i);
    }
});
t.start();

try {
    t.join();  // 等待t线程执行完毕
} catch (InterruptedException e) {
    e.printStackTrace();
}

System.out.println("主线程继续执行");

4.5 interrupt中断 #

java
Thread thread = new Thread(() -> {
    while (!Thread.currentThread().isInterrupted()) {
        System.out.println("运行中...");
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();  // 重新设置中断标志
            break;
        }
    }
});

thread.start();
Thread.sleep(3000);
thread.interrupt();  // 中断线程

五、线程优先级 #

java
Thread thread = new Thread(() -> {});

thread.setPriority(Thread.MIN_PRIORITY);   // 1
thread.setPriority(Thread.NORM_PRIORITY);  // 5(默认)
thread.setPriority(Thread.MAX_PRIORITY);   // 10

// 注意:优先级只是建议,不保证执行顺序

六、守护线程 #

java
Thread daemon = new Thread(() -> {
    while (true) {
        System.out.println("守护线程运行中...");
    }
});

daemon.setDaemon(true);  // 设置为守护线程
daemon.start();

// 当所有用户线程结束,守护线程自动结束

七、线程安全 #

7.1 线程安全问题 #

java
public class Counter {
    private int count = 0;
    
    public void increment() {
        count++;  // 非原子操作
    }
    
    public int getCount() {
        return count;
    }
}

// 多线程环境下,count可能不正确

7.2 synchronized关键字 #

java
public class Counter {
    private int count = 0;
    
    public synchronized void increment() {
        count++;
    }
    
    public synchronized int getCount() {
        return count;
    }
}

7.3 同步代码块 #

java
public class Counter {
    private int count = 0;
    private final Object lock = new Object();
    
    public void increment() {
        synchronized (lock) {
            count++;
        }
    }
}

八、总结 #

方法 说明
start() 启动线程
sleep() 休眠
yield() 让出CPU
join() 等待线程结束
interrupt() 中断线程

线程要点:

  • 优先使用Runnable接口
  • 注意线程安全问题
  • 使用synchronized保证同步
  • 合理使用线程优先级
最后更新:2026-03-26