← 返回首页 ❓ 面试题库
📑 本篇章节导航 (共8章,点击直达)
一、Java内存模型二、锁机制三、并发容器四、原子类与CAS五、线程池六、异步编程七、面试高频综合题面试速记口诀

Q133 并发编程与线程安全深度实战

20K Java+AI 岗位高频考点 — Java并发是后端开发的核心难点,面试必考synchronized原理、volatile语义、AQS框架、线程池、CAS。覆盖JMM、锁机制、并发容器、原子类、CompletableFuture、虚拟线程。

一、Java内存模型

1. JMM(Java Memory Model)?


JMM规定:线程如何与主内存交互

工作模型:
线程A                    主内存                    线程B
  │ ←── read ←──────────┤───────────→ read ──→ │
  │     load             │             load      │
  │     use              │             use       │
  │     assign           │             assign    │
  │     store ──────────→┤←────────── store     │
  │     write            │             write     │

三大特性:
1. 可见性(Visibility):一个线程的修改对其他线程立即可见
   → volatile / synchronized / Lock
2. 原子性(Atomicity):操作不可分割
   → synchronized / Lock / AtomicInteger
3. 有序性(Ordering):程序执行顺序符合预期
   → volatile禁止重排序 / happens-before规则

happens-before规则:
1. 程序顺序:同一线程内按代码顺序
2. volatile写→后续volatile读
3. synchronized解锁→后续加锁
4. 线程start→线程内任意操作
5. 线程内操作→线程join返回
6. 传递性:A→B, B→C → A→C

2. volatile原理?


volatile保证:可见性 + 有序性(不保证原子性)

底层实现:
1. 写操作:JVM指令加lock前缀
   → 将当前缓存行写回主内存
   → 使其他CPU缓存行失效(MESI协议)

2. 读操作:直接从主内存读取

3. 禁止指令重排序:内存屏障(Memory Barrier)
   StoreStore → volatile写 → StoreLoad
   LoadLoad → volatile读 → LoadStore

不保证原子性的例子:
volatile int count = 0;
// 两个线程同时count++,结果可能小于2
// 因为count++ = 读→加1→写(不是原子操作)

正确做法:
AtomicInteger count = new AtomicInteger();
count.incrementAndGet();  // CAS原子操作

使用场景:
1. 状态标志(boolean running)
2. 双重检查锁的单例
3. 读多写少且写不依赖当前值

3. synchronized原理?


synchronized三种用法:
1. 同步方法 → 锁当前实例(this)
2. 同步静态方法 → 锁Class对象
3. 同步代码块 → 锁指定对象

底层实现:
1. 代码块:monitorenter / monitorexit字节码
2. 方法:ACC_SYNCHRONIZED标志位

Monitor对象(Object Header):
| 锁状态 | 25bit   | 31bit      | 1bit   | 4bit  | 1bit(是否偏向) | 2bit(锁标志) |
|--------|---------|------------|--------|-------|---------------|-------------|
| 无锁   | unused  | hashCode   | unused | 分代年龄 | 0           | 01          |
| 偏向锁 | 线程ID  | epoch      | unused | 分代年龄 | 1           | 01          |
| 轻量锁 | 指向栈中锁记录的指针                               | 00          |
| 重量锁 | 指向Monitor对象的指针                              | 10          |

锁升级过程(不可降级):
无锁 → 偏向锁 → 轻量锁(自旋) → 重量锁

偏向锁:第一个线程获取,CAS记录线程ID
轻量锁:第二个线程竞争,CAS失败→自旋
重量锁:自旋失败→膨胀为重量锁→阻塞等待

二、锁机制

4. ReentrantLock vs synchronized?


| 维度 | synchronized | ReentrantLock |
|------|-------------|---------------|
| 实现 | JVM内置 | JDK API |
| 锁获取 | 自动 | 手动lock/unlock |
| 可中断 | 不可 | lockInterruptibly() |
| 超时 | 不支持 | tryLock(timeout) |
| 公平 | 非公平 | 可选公平/非公平 |
| 条件 | wait/notify | Condition(await/signal) |
| 可重入 | 是 | 是 |

ReentrantLock使用:
Lock lock = new ReentrantLock();
Condition notEmpty = lock.newCondition();
Condition notFull = lock.newCondition();

lock.lock();
try {
    while (queue.isEmpty()) notEmpty.await();
    Item item = queue.poll();
    notFull.signal();
    return item;
} finally {
    lock.unlock();  // 必须在finally中释放
}

选型:
- 简单同步 → synchronized(更安全,不会忘记unlock)
- 需要超时/中断/公平锁 → ReentrantLock

5. AQS(AbstractQueuedSynchronizer)?


AQS = Java并发锁的基石

核心数据结构:
- state(volatile int):同步状态
- CLH队列(双向链表):等待线程队列

state含义:
- ReentrantLock:0=未锁,>0=锁定(可重入次数)
- Semaphore:剩余许可数
- CountDownLatch:剩余计数
- ReentrantReadWriteLock:高16位读锁,低16位写锁

加锁流程(ReentrantLock为例):
1. tryAcquire:CAS尝试修改state(0→1)
2. 成功 → 获得锁
3. 失败 → 加入CLH队列尾 → park挂起
4. 前驱节点释放锁 → unpark唤醒 → 再次tryAcquire

源码关键方法(模板方法模式):
tryAcquire(int)      → 独占获取
tryRelease(int)      → 独占释放
tryAcquireShared(int)→ 共享获取
tryReleaseShared(int)→ 共享释放

基于AQS的实现:
ReentrantLock, ReentrantReadWriteLock, Semaphore,
CountDownLatch, CyclicBarrier

6. 读写锁(ReentrantReadWriteLock)?


// 读写分离:读不互斥,写互斥
ReadWriteLock rwLock = new ReentrantReadWriteLock();
Lock readLock = rwLock.readLock();
Lock writeLock = rwLock.writeLock();

// 读操作(多线程可同时读)
public Data getData(String key) {
    readLock.lock();
    try {
        return cache.get(key);
    } finally {
        readLock.unlock();
    }
}

// 写操作(独占)
public void putData(String key, Data data) {
    writeLock.lock();
    try {
        cache.put(key, data);
    } finally {
        writeLock.unlock();
    }
}

// 锁降级:写锁→读锁(可以,获取读锁后释放写锁)
writeLock.lock();
try {
    // 更新数据
    readLock.lock();  // 获取读锁
} finally {
    writeLock.unlock(); // 释放写锁,仍持有读锁
}
try {
    // 读取数据
} finally {
    readLock.unlock();
}
// 锁升级:读锁→写锁(不允许,会死锁)

三、并发容器

7. ConcurrentHashMap?


JDK 1.7:Segment分段锁(16段)
JDK 1.8+:CAS + synchronized(锁桶节点)

put流程:
1. 计算hash定位桶
2. 桶为空 → CAS写入
3. 桶不为空 → synchronized锁住头节点 → 遍历链表/红黑树
4. 链表长度≥8 → 树化为红黑树
5. 扩容:transfer(支持多线程协助扩容)

size():baseCount + CounterCell[](分散计数,类似LongAdder)

为什么不用Hashtable?
- Hashtable用synchronized锁整个表
- ConcurrentHashMap锁单个桶,并发度=桶数量

为什么不用HashMap?
- HashMap非线程安全
- 并发put可能导致链表成环→死循环

关键参数:
DEFAULT_INITIAL_CAPACITY = 16
DEFAULT_LOAD_FACTOR = 0.75f
TREEIFY_THRESHOLD = 8
UNTREEIFY_THRESHOLD = 6

8. 其他并发容器?


ConcurrentLinkedQueue:无界非阻塞队列(CAS)
LinkedBlockingQueue:可选有界阻塞队列(ReentrantLock)
ArrayBlockingQueue:有界阻塞队列(ReentrantLock)
PriorityBlockingQueue:优先级阻塞队列
SynchronousQueue:零容量队列(直接传递)
DelayQueue:延迟队列(元素到期才能取出)
LinkedTransferQueue:转移队列

CopyOnWriteArrayList:
- 读不加锁(直接读数组)
- 写时复制(CopyOnWrite)
- 适合读多写少(监听器列表、配置列表)

ConcurrentSkipListMap:
- 跳表实现的并发SortedMap
- 平均O(logN)查找
- 适合范围查询

选择:
高并发读写 → ConcurrentHashMap
读多写少 → CopyOnWriteArrayList
生产消费 → LinkedBlockingQueue / ArrayBlockingQueue
延迟处理 → DelayQueue

四、原子类与CAS

9. CAS原理?


CAS = Compare And Swap(比较并交换)

伪代码:
boolean cas(long offset, long expected, long newValue) {
    if (getValue(offset) == expected) {
        setValue(offset, newValue);
        return true;
    }
    return false;
}

底层:CPU的cmpxchg指令(原子操作)

ABA问题:
线程1: 读A → [A→B→A] → CAS(A,C) → 成功(但中间被改过)
解决:AtomicStampedReference(带版本号)

Atomic类:
AtomicInteger / AtomicLong / AtomicBoolean
AtomicReference / AtomicStampedReference
AtomicIntegerArray / AtomicLongArray
LongAdder / LongAccumulator(分散计数,高并发优于AtomicLong)

LongAdder原理:
分散热点 → Cell[]数组 → 每个线程对不同Cell做CAS
sum() = base + 所有Cell的值(最终一致,不求精确快照)

10. ThreadLocal原理?


// 每个线程独立的变量副本
private static final ThreadLocal<SimpleDateFormat> dateFormat =
    ThreadLocal.withInitial(() -> new SimpleDateFormat("yyyy-MM-dd"));

// 使用
String date = dateFormat.get().format(new Date());

// 原理:
// Thread → ThreadLocalMap → Entry[ThreadLocal, value]
// 每个Thread持有自己的Map,Key是ThreadLocal(弱引用)

// 内存泄漏问题:
// ThreadLocal是弱引用 → GC时被回收 → Entry的key=null
// 但value仍被Entry引用 → 无法回收
// 解决:用完必须remove()
try {
    dateFormat.set(format);
    // 使用
} finally {
    dateFormat.remove();  // 必须清理
}

// 线程池中的ThreadLocal:
// 线程复用 → ThreadLocal值残留
// 解决:每次使用前set(),使用后remove()

// 阿里TransmittableThreadLocal(TTL):
// 线程池场景下传递ThreadLocal值

五、线程池

11. ThreadPoolExecutor?


ThreadPoolExecutor executor = new ThreadPoolExecutor(
    2,                              // corePoolSize
    4,                              // maximumPoolSize
    60, TimeUnit.SECONDS,           // keepAliveTime
    new LinkedBlockingQueue<>(100), // workQueue
    new ThreadFactory() {           // threadFactory
        private final AtomicInteger counter = new AtomicInteger();
        public Thread newThread(Runnable r) {
            Thread t = new Thread(r, "pool-" + counter.incrementAndGet());
            t.setDaemon(false);
            return t;
        }
    },
    new ThreadPoolExecutor.CallerRunsPolicy()  // rejectedHandler
);

// 执行流程:
// 1. 当前线程<corePoolSize → 创建新线程
// 2. 当前线程≥corePoolSize → 放入队列
// 3. 队列满 → 创建新线程(到maxPoolSize)
// 4. 队列满且线程≥maxPoolSize → 拒绝策略

// 拒绝策略:
// AbortPolicy → 抛异常(默认)
// CallerRunsPolicy → 调用者线程执行
// DiscardPolicy → 静默丢弃
// DiscardOldestPolicy → 丢弃最老任务

12. 线程池最佳实践?


// 禁止用Executors(阿里规约)
// Executors.newFixedThreadPool → 队列无界→OOM
// Executors.newCachedThreadPool → 线程无限→OOM

// 配置原则:
// CPU密集型:corePoolSize = CPU核心数 + 1
// IO密集型:corePoolSize = CPU核心数 × 2
// 混合型:根据IO等待比例计算
//   threads = cores × (1 + waitTime/computeTime)

// Spring Boot配置
@Configuration
public class ThreadPoolConfig {
    @Bean("orderExecutor")
    public ThreadPoolExecutor orderExecutor() {
        return new ThreadPoolExecutor(
            4, 8, 60, TimeUnit.SECONDS,
            new LinkedBlockingQueue<>(200),
            new CustomThreadFactory("order"),
            new ThreadPoolExecutor.CallerRunsPolicy());
    }
}

// 监控
executor.getActiveCount();    // 活跃线程数
executor.getQueue().size();   // 队列长度
executor.getCompletedTaskCount(); // 完成任务数
executor.getLargestPoolSize();    // 历史最大线程数

// 优雅关闭
executor.shutdown();
if (!executor.awaitTermination(30, TimeUnit.SECONDS)) {
    executor.shutdownNow();
}

六、异步编程

13. CompletableFuture?


// 创建
CompletableFuture<String> cf = CompletableFuture.supplyAsync(() -> {
    return "hello";
}, executor);

// 串行
cf.thenApply(s -> s + " world")        // 有返回值
  .thenAccept(s -> log.info(s))        // 无返回值
  .thenRun(() -> log.info("done"));    // 无输入无输出

// 组合
CompletableFuture<String> cf1 = CompletableFuture.supplyAsync(() -> "hello");
CompletableFuture<String> cf2 = CompletableFuture.supplyAsync(() -> "world");

// 两个都完成
cf1.thenCombine(cf2, (a, b) -> a + " " + b);

// 任一完成
cf1.acceptEither(cf2, s -> log.info(s));

// 全部完成
CompletableFuture.allOf(cf1, cf2, cf3).join();

// 异常处理
cf.exceptionally(ex -> "fallback")
  .handle((result, ex) -> ex != null ? "error" : result);

// 超时
cf.orTimeout(5, TimeUnit.SECONDS)
  .completeOnTimeout("default", 5, TimeUnit.SECONDS);

// 实战:并行调用多个服务
public OrderDetail getOrderDetail(Long orderId) {
    CompletableFuture<Order> orderCf = CompletableFuture.supplyAsync(
        () -> orderClient.getOrder(orderId), executor);
    CompletableFuture<User> userCf = CompletableFuture.supplyAsync(
        () -> userClient.getUser(order.getUserId()), executor);
    CompletableFuture<List<Log>> logCf = CompletableFuture.supplyAsync(
        () -> logClient.getLogs(orderId), executor);

    CompletableFuture.allOf(orderCf, userCf, logCf).join();
    return new OrderDetail(orderCf.join(), userCf.join(), logCf.join());
}

14. Java 21虚拟线程?


Virtual Thread = 轻量级线程(协程)

创建方式:
// 方式一
Thread.startVirtualThread(() -> System.out.println("hello"));

// 方式二
Thread vt = Thread.ofVirtual().name("my-vt").start(runnable);

// 方式三(推荐)
ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor();

与传统线程对比:
| 维度 | 平台线程 | 虚拟线程 |
|------|---------|---------|
| 创建成本 | 高(~1ms) | 极低(~μs) |
| 内存 | ~1MB/线程 | ~KB/线程 |
| 调度 | OS调度 | JVM调度 |
| 数量 | 几千 | 数百万 |
| 适合 | CPU密集 | IO密集 |

适合场景:
- 大量IO操作(HTTP调用、数据库查询)
- 每个请求一个线程(Thread-per-request)
- 不需要改造现有代码(同步写法,异步效果)

不适合:
- CPU密集(如加密、排序)
- 持有锁时间长(pinning问题)
- 使用synchronized + IO(会pin载体线程)
  → 改用ReentrantLock

Spring Boot 3.2+支持:
spring.threads.virtual.enabled=true
// 自动为Tomcat请求处理和Async任务使用虚拟线程

七、面试高频综合题

15. 如何避免死锁?


1. 按固定顺序加锁(最有效)
   // Bad:两个线程以不同顺序获取两把锁
   transfer(A, B) → lock(A) → lock(B)
   transfer(B, A) → lock(B) → lock(A) ← 死锁
   
   // Good:按ID排序
   lock(min(A.id, B.id)) → lock(max(A.id, B.id))

2. 使用tryLock超时
   if (lock.tryLock(100, TimeUnit.MILLISECONDS)) {
       try { ... } finally { lock.unlock(); }
   }

3. 减少锁粒度(锁更少的代码)
4. 避免嵌套锁
5. 使用无锁设计(CAS/ConcurrentHashMap)

16. synchronized锁优化?


JDK 1.6+锁优化:

1. 偏向锁(Biased Locking):
   第一个线程获取后记录线程ID
   后续同线程进入无需CAS(检查ID即可)
   适合:同一线程反复获取同一把锁

2. 轻量锁(Lightweight Lock):
   偏向锁竞争 → 撤销偏向 → 轻量锁
   CAS自旋(不阻塞线程)
   适合:少量线程短时间竞争

3. 重量锁(Heavyweight Lock):
   自旋失败 → 膨胀为重量锁
   线程阻塞(OS互斥量)
   适合:高竞争或持锁时间长

4. 自适应自旋(Adaptive Spinning):
   根据上次自旋是否成功决定自旋次数

5. 锁消除(Lock Elimination):
   JIT逃逸分析 → 不存在竞争 → 消除锁

6. 锁粗化(Lock Coarsening):
   多次相邻加锁解锁 → 合并为一次

17. ThreadLocal内存泄漏?


泄漏原因:
1. ThreadLocalMap的Entry继承WeakReference
2. Key(ThreadLocal)是弱引用 → GC时被回收
3. Key变成null → 但value仍被引用
4. 线程长期存活(线程池)→ value无法回收

预防:
try {
    threadLocal.set(value);
    // 使用
} finally {
    threadLocal.remove();  // 必须手动清理
}

线程池场景:
// 请求处理前清理
threadLocal.remove();
threadLocal.set(context);
try {
    handle(request);
} finally {
    threadLocal.remove();  // 请求结束清理
}

18. 并发编程实战:计数器?


// 方案一:AtomicLong(中等并发)
AtomicLong counter = new AtomicLong();
counter.incrementAndGet();  // CAS自旋

// 方案二:LongAdder(高并发,推荐)
LongAdder counter = new LongAdder();
counter.increment();
counter.sum();  // 最终一致

// 方案三:分布式计数(跨JVM)
@Autowired StringRedisTemplate redis;
redis.opsForValue().increment("counter:order");

// 方案四:分段锁(数据库级)
// 按ID取模分表,每个表独立计数

面试速记口诀

JMM三特性:可见性(volatile)、原子性(synchronized/CAS)、有序性(happens-before)

>

锁升级四阶段:无锁→偏向(记线程ID)→轻量(自旋)→重量(阻塞)

>

AQS核心:state状态+CLH队列+CAS,模板方法供子类实现

>

线程池三参数:core核心/max最大/queue队列,满了才扩到max再拒绝