Java多线程编程实战指南
1. 线程基础概念
-
线程状态
NEW、RUNNABLE、BLOCKED、WAITING、TIMED_WAITING、TERMINATED
-
线程优先级
1-10的整数,默认为5,数字越大优先级越高
-
守护线程
后台线程,当所有用户线程结束时,守护线程会自动结束
线程创建方式
// 1. 继承Thread类
class MyThread extends Thread {
@Override
public void run() {
// 线程执行代码
}
}
// 2. 实现Runnable接口
class MyRunnable implements Runnable {
@Override
public void run() {
// 线程执行代码
}
}
// 3. 使用Lambda表达式
Thread thread = new Thread(() -> {
// 线程执行代码
});
// 4. 使用线程池
ExecutorService executor = Executors.newFixedThreadPool(5);
executor.submit(() -> {
// 线程执行代码
});
2. 线程同步机制
2.1 synchronized关键字
public class Counter {
private int count = 0;
// 同步方法
public synchronized void increment() {
count++;
}
// 同步代码块
public void decrement() {
synchronized(this) {
count--;
}
}
}
2.2 Lock接口
private Lock lock = new ReentrantLock();
private Condition condition = lock.newCondition();
public void method() {
lock.lock();
try {
// 临界区代码
while(条件不满足) {
condition.await();
}
// 执行业务逻辑
condition.signalAll();
} finally {
lock.unlock();
}
}
死锁预防
- 避免嵌套锁
- 固定加锁顺序
- 使用超时机制
- 使用tryLock()方法
3. 线程池应用
3.1 常用线程池
// 固定大小线程池
ExecutorService fixedPool = Executors.newFixedThreadPool(5);
// 缓存线程池
ExecutorService cachedPool = Executors.newCachedThreadPool();
// 单线程池
ExecutorService singlePool = Executors.newSingleThreadExecutor();
// 调度线程池
ScheduledExecutorService scheduledPool =
Executors.newScheduledThreadPool(5);
3.2 自定义线程池
ThreadPoolExecutor executor = new ThreadPoolExecutor(
5, // 核心线程数
10, // 最大线程数
60L, // 空闲线程存活时间
TimeUnit.SECONDS, // 时间单位
new LinkedBlockingQueue<>(100), // 任务队列
new ThreadPoolExecutor.CallerRunsPolicy() // 拒绝策略
);
4. 并发工具类
4.1 CountDownLatch
CountDownLatch latch = new CountDownLatch(3);
// 工作线程
new Thread(() -> {
// 执行任务
latch.countDown();
}).start();
// 等待所有任务完成
latch.await();
4.2 CyclicBarrier
CyclicBarrier barrier = new CyclicBarrier(3, () -> {
// 所有线程到达屏障时执行
System.out.println("All threads arrived");
});
// 等待其他线程
barrier.await();