并发编程详解
00:00
Java并发编程详解:synchronized、Lock、AQS、原子类、线程池。
1. synchronized
// 修饰实例方法:锁当前对象
public synchronized void method() {}
// 修饰静态方法:锁 Class 对象
public static synchronized void method() {}
// 修饰代码块
synchronized(obj) { /* 临界区 */ }
2. Lock 接口
ReentrantLock lock = new ReentrantLock();
lock.lock();
try {
// 临界区
} finally {
lock.unlock(); // 必须在 finally 中释放
}
// 可中断锁
lock.lockInterruptibly();
// 尝试获取锁
if (lock.tryLock(1, TimeUnit.SECONDS)) {
try { /* ... */ } finally { lock.unlock(); }
}
3. AQS 原理
AbstractQueuedSynchronizer 是 Lock 的实现基础:
- 内部维护一个 volatile int state 和一个 FIFO 等待队列
- ReentrantLock: state = 0 未锁定,> 0 锁定次数
- Semaphore: state = 许可数
- CountDownLatch: state = 计数器
4. 原子类
AtomicInteger count = new AtomicInteger(0);
count.incrementAndGet(); // CAS +1
count.compareAndSet(0, 1); // CAS 操作
LongAdder adder = new LongAdder(); // 高并发下更优
adder.add(1);
5. 线程池
ThreadPoolExecutor pool = new ThreadPoolExecutor(
4, // 核心线程数
8, // 最大线程数
60, TimeUnit.SECONDS, // 空闲线程存活时间
new LinkedBlockingQueue<>(100), // 任务队列
new ThreadPoolExecutor.CallerRunsPolicy() // 拒绝策略
);