并发的基石:深入浅出 Java 线程同步机制
-
- 1. 引言:从多线程的混乱到有序
- 2. 一图看懂:什么是线程同步?
- 3. 为什么需要同步:问题演示
-
- 3.1 一个经典的并发问题
- 3.2 count++ 的非原子性分析
- 4. Java 同步机制全景图
- 5. synchronized:Java 最基础的同步机制
-
- 5.1 synchronized 的三种用法
- 5.2 锁的获取与释放流程
- 5.3 解决之前的计数器问题
- 6. ReentrantLock:更灵活的锁
-
- 6.1 基本用法
- 6.2 synchronized vs ReentrantLock
- 7. 原子类:无锁同步
-
- 7.1 原子类的原理
- 7.2 原子类示例
- 7.3 常用原子类对比
- 8. 条件变量:线程间的协作
-
- 8.1 wait/notify 机制
- 8.2 Condition 接口(ReentrantLock)
- 9. 其他同步工具
-
- 9.1 volatile:轻量级同步
- 9.2 ThreadLocal:线程隔离
- 10. 同步策略选择指南
-
- 10.1 选择决策表
- 11. 常见问题与最佳实践
-
- 11.1 死锁及其避免
- 11.2 锁粒度控制
- 11.3 最小化同步块
- 12. 总结
|
🌺The Begin🌺点点关注,收藏不迷路🌺 |
1. 引言:从多线程的混乱到有序
想象这样一个场景:你和家人共用一张银行卡,你去 ATM 取钱的同时,你的家人也在柜台取钱。如果没有任何协调机制,账户余额可能变成负数,这显然是不允许的。
Java 多线程编程中同样存在这个问题——多个线程同时访问共享资源时,会产生数据不一致的问题。而线程同步,就是解决这个问题的核心手段。
本文将全面介绍 Java 中的线程同步机制,从基本概念到高级工具,助你彻底掌握并发编程的精髓。
2. 一图看懂:什么是线程同步?
#mermaid-svg-K0RsUA73J7Cpiiko{font-family:\”trebuchet ms\”,verdana,arial,sans-serif;font-size:16px;fill:#333;}@keyframes edge-animation-frame{from{stroke-dashoffset:0;}}@keyframes dash{to{stroke-dashoffset:0;}}#mermaid-svg-K0RsUA73J7Cpiiko .edge-animation-slow{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 50s linear infinite;stroke-linecap:round;}#mermaid-svg-K0RsUA73J7Cpiiko .edge-animation-fast{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 20s linear infinite;stroke-linecap:round;}#mermaid-svg-K0RsUA73J7Cpiiko .error-icon{fill:#552222;}#mermaid-svg-K0RsUA73J7Cpiiko .error-text{fill:#552222;stroke:#552222;}#mermaid-svg-K0RsUA73J7Cpiiko .edge-thickness-normal{stroke-width:1px;}#mermaid-svg-K0RsUA73J7Cpiiko .edge-thickness-thick{stroke-width:3.5px;}#mermaid-svg-K0RsUA73J7Cpiiko .edge-pattern-solid{stroke-dasharray:0;}#mermaid-svg-K0RsUA73J7Cpiiko .edge-thickness-invisible{stroke-width:0;fill:none;}#mermaid-svg-K0RsUA73J7Cpiiko .edge-pattern-dashed{stroke-dasharray:3;}#mermaid-svg-K0RsUA73J7Cpiiko .edge-pattern-dotted{stroke-dasharray:2;}#mermaid-svg-K0RsUA73J7Cpiiko .marker{fill:#333333;stroke:#333333;}#mermaid-svg-K0RsUA73J7Cpiiko .marker.cross{stroke:#333333;}#mermaid-svg-K0RsUA73J7Cpiiko svg{font-family:\”trebuchet ms\”,verdana,arial,sans-serif;font-size:16px;}#mermaid-svg-K0RsUA73J7Cpiiko p{margin:0;}#mermaid-svg-K0RsUA73J7Cpiiko .label{font-family:\”trebuchet ms\”,verdana,arial,sans-serif;color:#333;}#mermaid-svg-K0RsUA73J7Cpiiko .cluster-label text{fill:#333;}#mermaid-svg-K0RsUA73J7Cpiiko .cluster-label span{color:#333;}#mermaid-svg-K0RsUA73J7Cpiiko .cluster-label span p{background-color:transparent;}#mermaid-svg-K0RsUA73J7Cpiiko .label text,#mermaid-svg-K0RsUA73J7Cpiiko span{fill:#333;color:#333;}#mermaid-svg-K0RsUA73J7Cpiiko .node rect,#mermaid-svg-K0RsUA73J7Cpiiko .node circle,#mermaid-svg-K0RsUA73J7Cpiiko .node ellipse,#mermaid-svg-K0RsUA73J7Cpiiko .node polygon,#mermaid-svg-K0RsUA73J7Cpiiko .node path{fill:#ECECFF;stroke:#9370DB;stroke-width:1px;}#mermaid-svg-K0RsUA73J7Cpiiko .rough-node .label text,#mermaid-svg-K0RsUA73J7Cpiiko .node .label text,#mermaid-svg-K0RsUA73J7Cpiiko .image-shape .label,#mermaid-svg-K0RsUA73J7Cpiiko .icon-shape .label{text-anchor:middle;}#mermaid-svg-K0RsUA73J7Cpiiko .node .katex path{fill:#000;stroke:#000;stroke-width:1px;}#mermaid-svg-K0RsUA73J7Cpiiko .rough-node .label,#mermaid-svg-K0RsUA73J7Cpiiko .node .label,#mermaid-svg-K0RsUA73J7Cpiiko .image-shape .label,#mermaid-svg-K0RsUA73J7Cpiiko .icon-shape .label{text-align:center;}#mermaid-svg-K0RsUA73J7Cpiiko .node.clickable{cursor:pointer;}#mermaid-svg-K0RsUA73J7Cpiiko .root .anchor path{fill:#333333!important;stroke-width:0;stroke:#333333;}#mermaid-svg-K0RsUA73J7Cpiiko .arrowheadPath{fill:#333333;}#mermaid-svg-K0RsUA73J7Cpiiko .edgePath .path{stroke:#333333;stroke-width:2.0px;}#mermaid-svg-K0RsUA73J7Cpiiko .flowchart-link{stroke:#333333;fill:none;}#mermaid-svg-K0RsUA73J7Cpiiko .edgeLabel{background-color:rgba(232,232,232, 0.8);text-align:center;}#mermaid-svg-K0RsUA73J7Cpiiko .edgeLabel p{background-color:rgba(232,232,232, 0.8);}#mermaid-svg-K0RsUA73J7Cpiiko .edgeLabel rect{opacity:0.5;background-color:rgba(232,232,232, 0.8);fill:rgba(232,232,232, 0.8);}#mermaid-svg-K0RsUA73J7Cpiiko .labelBkg{background-color:rgba(232, 232, 232, 0.5);}#mermaid-svg-K0RsUA73J7Cpiiko .cluster rect{fill:#ffffde;stroke:#aaaa33;stroke-width:1px;}#mermaid-svg-K0RsUA73J7Cpiiko .cluster text{fill:#333;}#mermaid-svg-K0RsUA73J7Cpiiko .cluster span{color:#333;}#mermaid-svg-K0RsUA73J7Cpiiko div.mermaidTooltip{position:absolute;text-align:center;max-width:200px;padding:2px;font-family:\”trebuchet ms\”,verdana,arial,sans-serif;font-size:12px;background:hsl(80, 100%, 96.2745098039%);border:1px solid #aaaa33;border-radius:2px;pointer-events:none;z-index:100;}#mermaid-svg-K0RsUA73J7Cpiiko .flowchartTitleText{text-anchor:middle;font-size:18px;fill:#333;}#mermaid-svg-K0RsUA73J7Cpiiko rect.text{fill:none;stroke-width:0;}#mermaid-svg-K0RsUA73J7Cpiiko .icon-shape,#mermaid-svg-K0RsUA73J7Cpiiko .image-shape{background-color:rgba(232,232,232, 0.8);text-align:center;}#mermaid-svg-K0RsUA73J7Cpiiko .icon-shape p,#mermaid-svg-K0RsUA73J7Cpiiko .image-shape p{background-color:rgba(232,232,232, 0.8);padding:2px;}#mermaid-svg-K0RsUA73J7Cpiiko .icon-shape .label rect,#mermaid-svg-K0RsUA73J7Cpiiko .image-shape .label rect{opacity:0.5;background-color:rgba(232,232,232, 0.8);fill:rgba(232,232,232, 0.8);}#mermaid-svg-K0RsUA73J7Cpiiko .label-icon{display:inline-block;height:1em;overflow:visible;vertical-align:-0.125em;}#mermaid-svg-K0RsUA73J7Cpiiko .node .label-icon path{fill:currentColor;stroke:revert;stroke-width:revert;}#mermaid-svg-K0RsUA73J7Cpiiko :root{–mermaid-font-family:\”trebuchet ms\”,verdana,arial,sans-serif;}
✅ 同步后的状态
等待
等待
同步机制
锁/信号量
线程1
线程2
线程3
安全访问
❌ 未同步的状态
线程1
共享资源
线程2
线程3
数据混乱
脏读
丢失更新
核心概念:
线程同步是指当多个线程访问共享资源时,通过某种机制确保资源在同一时刻只能被一个线程使用,从而保证数据的正确性和一致性。
3. 为什么需要同步:问题演示
3.1 一个经典的并发问题
public class UnsafeCounter {
private int count = 0;
public void increment() {
count++; // 这不是原子操作!
}
public int getCount() {
return count;
}
public static void main(String[] args) throws InterruptedException {
UnsafeCounter counter = new UnsafeCounter();
Thread[] threads = new Thread[1000];
for (int i = 0; i < 1000; i++) {
threads[i] = new Thread(() -> {
for (int j = 0; j < 1000; j++) {
counter.increment();
}
});
threads[i].start();
}
for (Thread t : threads) {
t.join();
}
System.out.println("Expected: 1000000, Actual: " + counter.getCount());
// 实际输出可能是 998765 之类的,小于预期值
}
}
3.2 count++ 的非原子性分析
#mermaid-svg-t3bOct02iOhN0oIa{font-family:\”trebuchet ms\”,verdana,arial,sans-serif;font-size:16px;fill:#333;}@keyframes edge-animation-frame{from{stroke-dashoffset:0;}}@keyframes dash{to{stroke-dashoffset:0;}}#mermaid-svg-t3bOct02iOhN0oIa .edge-animation-slow{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 50s linear infinite;stroke-linecap:round;}#mermaid-svg-t3bOct02iOhN0oIa .edge-animation-fast{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 20s linear infinite;stroke-linecap:round;}#mermaid-svg-t3bOct02iOhN0oIa .error-icon{fill:#552222;}#mermaid-svg-t3bOct02iOhN0oIa .error-text{fill:#552222;stroke:#552222;}#mermaid-svg-t3bOct02iOhN0oIa .edge-thickness-normal{stroke-width:1px;}#mermaid-svg-t3bOct02iOhN0oIa .edge-thickness-thick{stroke-width:3.5px;}#mermaid-svg-t3bOct02iOhN0oIa .edge-pattern-solid{stroke-dasharray:0;}#mermaid-svg-t3bOct02iOhN0oIa .edge-thickness-invisible{stroke-width:0;fill:none;}#mermaid-svg-t3bOct02iOhN0oIa .edge-pattern-dashed{stroke-dasharray:3;}#mermaid-svg-t3bOct02iOhN0oIa .edge-pattern-dotted{stroke-dasharray:2;}#mermaid-svg-t3bOct02iOhN0oIa .marker{fill:#333333;stroke:#333333;}#mermaid-svg-t3bOct02iOhN0oIa .marker.cross{stroke:#333333;}#mermaid-svg-t3bOct02iOhN0oIa svg{font-family:\”trebuchet ms\”,verdana,arial,sans-serif;font-size:16px;}#mermaid-svg-t3bOct02iOhN0oIa p{margin:0;}#mermaid-svg-t3bOct02iOhN0oIa .label{font-family:\”trebuchet ms\”,verdana,arial,sans-serif;color:#333;}#mermaid-svg-t3bOct02iOhN0oIa .cluster-label text{fill:#333;}#mermaid-svg-t3bOct02iOhN0oIa .cluster-label span{color:#333;}#mermaid-svg-t3bOct02iOhN0oIa .cluster-label span p{background-color:transparent;}#mermaid-svg-t3bOct02iOhN0oIa .label text,#mermaid-svg-t3bOct02iOhN0oIa span{fill:#333;color:#333;}#mermaid-svg-t3bOct02iOhN0oIa .node rect,#mermaid-svg-t3bOct02iOhN0oIa .node circle,#mermaid-svg-t3bOct02iOhN0oIa .node ellipse,#mermaid-svg-t3bOct02iOhN0oIa .node polygon,#mermaid-svg-t3bOct02iOhN0oIa .node path{fill:#ECECFF;stroke:#9370DB;stroke-width:1px;}#mermaid-svg-t3bOct02iOhN0oIa .rough-node .label text,#mermaid-svg-t3bOct02iOhN0oIa .node .label text,#mermaid-svg-t3bOct02iOhN0oIa .image-shape .label,#mermaid-svg-t3bOct02iOhN0oIa .icon-shape .label{text-anchor:middle;}#mermaid-svg-t3bOct02iOhN0oIa .node .katex path{fill:#000;stroke:#000;stroke-width:1px;}#mermaid-svg-t3bOct02iOhN0oIa .rough-node .label,#mermaid-svg-t3bOct02iOhN0oIa .node .label,#mermaid-svg-t3bOct02iOhN0oIa .image-shape .label,#mermaid-svg-t3bOct02iOhN0oIa .icon-shape .label{text-align:center;}#mermaid-svg-t3bOct02iOhN0oIa .node.clickable{cursor:pointer;}#mermaid-svg-t3bOct02iOhN0oIa .root .anchor path{fill:#333333!important;stroke-width:0;stroke:#333333;}#mermaid-svg-t3bOct02iOhN0oIa .arrowheadPath{fill:#333333;}#mermaid-svg-t3bOct02iOhN0oIa .edgePath .path{stroke:#333333;stroke-width:2.0px;}#mermaid-svg-t3bOct02iOhN0oIa .flowchart-link{stroke:#333333;fill:none;}#mermaid-svg-t3bOct02iOhN0oIa .edgeLabel{background-color:rgba(232,232,232, 0.8);text-align:center;}#mermaid-svg-t3bOct02iOhN0oIa .edgeLabel p{background-color:rgba(232,232,232, 0.8);}#mermaid-svg-t3bOct02iOhN0oIa .edgeLabel rect{opacity:0.5;background-color:rgba(232,232,232, 0.8);fill:rgba(232,232,232, 0.8);}#mermaid-svg-t3bOct02iOhN0oIa .labelBkg{background-color:rgba(232, 232, 232, 0.5);}#mermaid-svg-t3bOct02iOhN0oIa .cluster rect{fill:#ffffde;stroke:#aaaa33;stroke-width:1px;}#mermaid-svg-t3bOct02iOhN0oIa .cluster text{fill:#333;}#mermaid-svg-t3bOct02iOhN0oIa .cluster span{color:#333;}#mermaid-svg-t3bOct02iOhN0oIa div.mermaidTooltip{position:absolute;text-align:center;max-width:200px;padding:2px;font-family:\”trebuchet ms\”,verdana,arial,sans-serif;font-size:12px;background:hsl(80, 100%, 96.2745098039%);border:1px solid #aaaa33;border-radius:2px;pointer-events:none;z-index:100;}#mermaid-svg-t3bOct02iOhN0oIa .flowchartTitleText{text-anchor:middle;font-size:18px;fill:#333;}#mermaid-svg-t3bOct02iOhN0oIa rect.text{fill:none;stroke-width:0;}#mermaid-svg-t3bOct02iOhN0oIa .icon-shape,#mermaid-svg-t3bOct02iOhN0oIa .image-shape{background-color:rgba(232,232,232, 0.8);text-align:center;}#mermaid-svg-t3bOct02iOhN0oIa .icon-shape p,#mermaid-svg-t3bOct02iOhN0oIa .image-shape p{background-color:rgba(232,232,232, 0.8);padding:2px;}#mermaid-svg-t3bOct02iOhN0oIa .icon-shape .label rect,#mermaid-svg-t3bOct02iOhN0oIa .image-shape .label rect{opacity:0.5;background-color:rgba(232,232,232, 0.8);fill:rgba(232,232,232, 0.8);}#mermaid-svg-t3bOct02iOhN0oIa .label-icon{display:inline-block;height:1em;overflow:visible;vertical-align:-0.125em;}#mermaid-svg-t3bOct02iOhN0oIa .node .label-icon path{fill:currentColor;stroke:revert;stroke-width:revert;}#mermaid-svg-t3bOct02iOhN0oIa :root{–mermaid-font-family:\”trebuchet ms\”,verdana,arial,sans-serif;}
并发干扰场景
线程1: 读取 count=5
线程1: 计算 5+1=6
线程2: 读取 count=5
线程2: 计算 5+1=6
线程1: 写回 count=6
线程2: 写回 count=6
结果: 两次自增后 count=6
count++ 的三个步骤
读取 count 值
count + 1
写回 count
结果:两个线程各执行一次 increment,期望值应该是 7,实际却是 6——这就是典型的丢失更新问题。
4. Java 同步机制全景图
#mermaid-svg-jvqjWPVhfzXmyGKz{font-family:\”trebuchet ms\”,verdana,arial,sans-serif;font-size:16px;fill:#333;}@keyframes edge-animation-frame{from{stroke-dashoffset:0;}}@keyframes dash{to{stroke-dashoffset:0;}}#mermaid-svg-jvqjWPVhfzXmyGKz .edge-animation-slow{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 50s linear infinite;stroke-linecap:round;}#mermaid-svg-jvqjWPVhfzXmyGKz .edge-animation-fast{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 20s linear infinite;stroke-linecap:round;}#mermaid-svg-jvqjWPVhfzXmyGKz .error-icon{fill:#552222;}#mermaid-svg-jvqjWPVhfzXmyGKz .error-text{fill:#552222;stroke:#552222;}#mermaid-svg-jvqjWPVhfzXmyGKz .edge-thickness-normal{stroke-width:1px;}#mermaid-svg-jvqjWPVhfzXmyGKz .edge-thickness-thick{stroke-width:3.5px;}#mermaid-svg-jvqjWPVhfzXmyGKz .edge-pattern-solid{stroke-dasharray:0;}#mermaid-svg-jvqjWPVhfzXmyGKz .edge-thickness-invisible{stroke-width:0;fill:none;}#mermaid-svg-jvqjWPVhfzXmyGKz .edge-pattern-dashed{stroke-dasharray:3;}#mermaid-svg-jvqjWPVhfzXmyGKz .edge-pattern-dotted{stroke-dasharray:2;}#mermaid-svg-jvqjWPVhfzXmyGKz .marker{fill:#333333;stroke:#333333;}#mermaid-svg-jvqjWPVhfzXmyGKz .marker.cross{stroke:#333333;}#mermaid-svg-jvqjWPVhfzXmyGKz svg{font-family:\”trebuchet ms\”,verdana,arial,sans-serif;font-size:16px;}#mermaid-svg-jvqjWPVhfzXmyGKz p{margin:0;}#mermaid-svg-jvqjWPVhfzXmyGKz .edge{stroke-width:3;}#mermaid-svg-jvqjWPVhfzXmyGKz .section–1 rect,#mermaid-svg-jvqjWPVhfzXmyGKz .section–1 path,#mermaid-svg-jvqjWPVhfzXmyGKz .section–1 circle,#mermaid-svg-jvqjWPVhfzXmyGKz .section–1 polygon,#mermaid-svg-jvqjWPVhfzXmyGKz .section–1 path{fill:hsl(240, 100%, 76.2745098039%);}#mermaid-svg-jvqjWPVhfzXmyGKz .section–1 text{fill:#ffffff;}#mermaid-svg-jvqjWPVhfzXmyGKz .node-icon–1{font-size:40px;color:#ffffff;}#mermaid-svg-jvqjWPVhfzXmyGKz .section-edge–1{stroke:hsl(240, 100%, 76.2745098039%);}#mermaid-svg-jvqjWPVhfzXmyGKz .edge-depth–1{stroke-width:17;}#mermaid-svg-jvqjWPVhfzXmyGKz .section–1 line{stroke:hsl(60, 100%, 86.2745098039%);stroke-width:3;}#mermaid-svg-jvqjWPVhfzXmyGKz .disabled,#mermaid-svg-jvqjWPVhfzXmyGKz .disabled circle,#mermaid-svg-jvqjWPVhfzXmyGKz .disabled text{fill:lightgray;}#mermaid-svg-jvqjWPVhfzXmyGKz .disabled text{fill:#efefef;}#mermaid-svg-jvqjWPVhfzXmyGKz .section-0 rect,#mermaid-svg-jvqjWPVhfzXmyGKz .section-0 path,#mermaid-svg-jvqjWPVhfzXmyGKz .section-0 circle,#mermaid-svg-jvqjWPVhfzXmyGKz .section-0 polygon,#mermaid-svg-jvqjWPVhfzXmyGKz .section-0 path{fill:hsl(60, 100%, 73.5294117647%);}#mermaid-svg-jvqjWPVhfzXmyGKz .section-0 text{fill:black;}#mermaid-svg-jvqjWPVhfzXmyGKz .node-icon-0{font-size:40px;color:black;}#mermaid-svg-jvqjWPVhfzXmyGKz .section-edge-0{stroke:hsl(60, 100%, 73.5294117647%);}#mermaid-svg-jvqjWPVhfzXmyGKz .edge-depth-0{stroke-width:14;}#mermaid-svg-jvqjWPVhfzXmyGKz .section-0 line{stroke:hsl(240, 100%, 83.5294117647%);stroke-width:3;}#mermaid-svg-jvqjWPVhfzXmyGKz .disabled,#mermaid-svg-jvqjWPVhfzXmyGKz .disabled circle,#mermaid-svg-jvqjWPVhfzXmyGKz .disabled text{fill:lightgray;}#mermaid-svg-jvqjWPVhfzXmyGKz .disabled text{fill:#efefef;}#mermaid-svg-jvqjWPVhfzXmyGKz .section-1 rect,#mermaid-svg-jvqjWPVhfzXmyGKz .section-1 path,#mermaid-svg-jvqjWPVhfzXmyGKz .section-1 circle,#mermaid-svg-jvqjWPVhfzXmyGKz .section-1 polygon,#mermaid-svg-jvqjWPVhfzXmyGKz .section-1 path{fill:hsl(80, 100%, 76.2745098039%);}#mermaid-svg-jvqjWPVhfzXmyGKz .section-1 text{fill:black;}#mermaid-svg-jvqjWPVhfzXmyGKz .node-icon-1{font-size:40px;color:black;}#mermaid-svg-jvqjWPVhfzXmyGKz .section-edge-1{stroke:hsl(80, 100%, 76.2745098039%);}#mermaid-svg-jvqjWPVhfzXmyGKz .edge-depth-1{stroke-width:11;}#mermaid-svg-jvqjWPVhfzXmyGKz .section-1 line{stroke:hsl(260, 100%, 86.2745098039%);stroke-width:3;}#mermaid-svg-jvqjWPVhfzXmyGKz .disabled,#mermaid-svg-jvqjWPVhfzXmyGKz .disabled circle,#mermaid-svg-jvqjWPVhfzXmyGKz .disabled text{fill:lightgray;}#mermaid-svg-jvqjWPVhfzXmyGKz .disabled text{fill:#efefef;}#mermaid-svg-jvqjWPVhfzXmyGKz .section-2 rect,#mermaid-svg-jvqjWPVhfzXmyGKz .section-2 path,#mermaid-svg-jvqjWPVhfzXmyGKz .section-2 circle,#mermaid-svg-jvqjWPVhfzXmyGKz .section-2 polygon,#mermaid-svg-jvqjWPVhfzXmyGKz .section-2 path{fill:hsl(270, 100%, 76.2745098039%);}#mermaid-svg-jvqjWPVhfzXmyGKz .section-2 text{fill:#ffffff;}#mermaid-svg-jvqjWPVhfzXmyGKz .node-icon-2{font-size:40px;color:#ffffff;}#mermaid-svg-jvqjWPVhfzXmyGKz .section-edge-2{stroke:hsl(270, 100%, 76.2745098039%);}#mermaid-svg-jvqjWPVhfzXmyGKz .edge-depth-2{stroke-width:8;}#mermaid-svg-jvqjWPVhfzXmyGKz .section-2 line{stroke:hsl(90, 100%, 86.2745098039%);stroke-width:3;}#mermaid-svg-jvqjWPVhfzXmyGKz .disabled,#mermaid-svg-jvqjWPVhfzXmyGKz .disabled circle,#mermaid-svg-jvqjWPVhfzXmyGKz .disabled text{fill:lightgray;}#mermaid-svg-jvqjWPVhfzXmyGKz .disabled text{fill:#efefef;}#mermaid-svg-jvqjWPVhfzXmyGKz .section-3 rect,#mermaid-svg-jvqjWPVhfzXmyGKz .section-3 path,#mermaid-svg-jvqjWPVhfzXmyGKz .section-3 circle,#mermaid-svg-jvqjWPVhfzXmyGKz .section-3 polygon,#mermaid-svg-jvqjWPVhfzXmyGKz .section-3 path{fill:hsl(300, 100%, 76.2745098039%);}#mermaid-svg-jvqjWPVhfzXmyGKz .section-3 text{fill:black;}#mermaid-svg-jvqjWPVhfzXmyGKz .node-icon-3{font-size:40px;color:black;}#mermaid-svg-jvqjWPVhfzXmyGKz .section-edge-3{stroke:hsl(300, 100%, 76.2745098039%);}#mermaid-svg-jvqjWPVhfzXmyGKz .edge-depth-3{stroke-width:5;}#mermaid-svg-jvqjWPVhfzXmyGKz .section-3 line{stroke:hsl(120, 100%, 86.2745098039%);stroke-width:3;}#mermaid-svg-jvqjWPVhfzXmyGKz .disabled,#mermaid-svg-jvqjWPVhfzXmyGKz .disabled circle,#mermaid-svg-jvqjWPVhfzXmyGKz .disabled text{fill:lightgray;}#mermaid-svg-jvqjWPVhfzXmyGKz .disabled text{fill:#efefef;}#mermaid-svg-jvqjWPVhfzXmyGKz .section-4 rect,#mermaid-svg-jvqjWPVhfzXmyGKz .section-4 path,#mermaid-svg-jvqjWPVhfzXmyGKz .section-4 circle,#mermaid-svg-jvqjWPVhfzXmyGKz .section-4 polygon,#mermaid-svg-jvqjWPVhfzXmyGKz .section-4 path{fill:hsl(330, 100%, 76.2745098039%);}#mermaid-svg-jvqjWPVhfzXmyGKz .section-4 text{fill:black;}#mermaid-svg-jvqjWPVhfzXmyGKz .node-icon-4{font-size:40px;color:black;}#mermaid-svg-jvqjWPVhfzXmyGKz .section-edge-4{stroke:hsl(330, 100%, 76.2745098039%);}#mermaid-svg-jvqjWPVhfzXmyGKz .edge-depth-4{stroke-width:2;}#mermaid-svg-jvqjWPVhfzXmyGKz .section-4 line{stroke:hsl(150, 100%, 86.2745098039%);stroke-width:3;}#mermaid-svg-jvqjWPVhfzXmyGKz .disabled,#mermaid-svg-jvqjWPVhfzXmyGKz .disabled circle,#mermaid-svg-jvqjWPVhfzXmyGKz .disabled text{fill:lightgray;}#mermaid-svg-jvqjWPVhfzXmyGKz .disabled text{fill:#efefef;}#mermaid-svg-jvqjWPVhfzXmyGKz .section-5 rect,#mermaid-svg-jvqjWPVhfzXmyGKz .section-5 path,#mermaid-svg-jvqjWPVhfzXmyGKz .section-5 circle,#mermaid-svg-jvqjWPVhfzXmyGKz .section-5 polygon,#mermaid-svg-jvqjWPVhfzXmyGKz .section-5 path{fill:hsl(0, 100%, 76.2745098039%);}#mermaid-svg-jvqjWPVhfzXmyGKz .section-5 text{fill:black;}#mermaid-svg-jvqjWPVhfzXmyGKz .node-icon-5{font-size:40px;color:black;}#mermaid-svg-jvqjWPVhfzXmyGKz .section-edge-5{stroke:hsl(0, 100%, 76.2745098039%);}#mermaid-svg-jvqjWPVhfzXmyGKz .edge-depth-5{stroke-width:-1;}#mermaid-svg-jvqjWPVhfzXmyGKz .section-5 line{stroke:hsl(180, 100%, 86.2745098039%);stroke-width:3;}#mermaid-svg-jvqjWPVhfzXmyGKz .disabled,#mermaid-svg-jvqjWPVhfzXmyGKz .disabled circle,#mermaid-svg-jvqjWPVhfzXmyGKz .disabled text{fill:lightgray;}#mermaid-svg-jvqjWPVhfzXmyGKz .disabled text{fill:#efefef;}#mermaid-svg-jvqjWPVhfzXmyGKz .section-6 rect,#mermaid-svg-jvqjWPVhfzXmyGKz .section-6 path,#mermaid-svg-jvqjWPVhfzXmyGKz .section-6 circle,#mermaid-svg-jvqjWPVhfzXmyGKz .section-6 polygon,#mermaid-svg-jvqjWPVhfzXmyGKz .section-6 path{fill:hsl(30, 100%, 76.2745098039%);}#mermaid-svg-jvqjWPVhfzXmyGKz .section-6 text{fill:black;}#mermaid-svg-jvqjWPVhfzXmyGKz .node-icon-6{font-size:40px;color:black;}#mermaid-svg-jvqjWPVhfzXmyGKz .section-edge-6{stroke:hsl(30, 100%, 76.2745098039%);}#mermaid-svg-jvqjWPVhfzXmyGKz .edge-depth-6{stroke-width:-4;}#mermaid-svg-jvqjWPVhfzXmyGKz .section-6 line{stroke:hsl(210, 100%, 86.2745098039%);stroke-width:3;}#mermaid-svg-jvqjWPVhfzXmyGKz .disabled,#mermaid-svg-jvqjWPVhfzXmyGKz .disabled circle,#mermaid-svg-jvqjWPVhfzXmyGKz .disabled text{fill:lightgray;}#mermaid-svg-jvqjWPVhfzXmyGKz .disabled text{fill:#efefef;}#mermaid-svg-jvqjWPVhfzXmyGKz .section-7 rect,#mermaid-svg-jvqjWPVhfzXmyGKz .section-7 path,#mermaid-svg-jvqjWPVhfzXmyGKz .section-7 circle,#mermaid-svg-jvqjWPVhfzXmyGKz .section-7 polygon,#mermaid-svg-jvqjWPVhfzXmyGKz .section-7 path{fill:hsl(90, 100%, 76.2745098039%);}#mermaid-svg-jvqjWPVhfzXmyGKz .section-7 text{fill:black;}#mermaid-svg-jvqjWPVhfzXmyGKz .node-icon-7{font-size:40px;color:black;}#mermaid-svg-jvqjWPVhfzXmyGKz .section-edge-7{stroke:hsl(90, 100%, 76.2745098039%);}#mermaid-svg-jvqjWPVhfzXmyGKz .edge-depth-7{stroke-width:-7;}#mermaid-svg-jvqjWPVhfzXmyGKz .section-7 line{stroke:hsl(270, 100%, 86.2745098039%);stroke-width:3;}#mermaid-svg-jvqjWPVhfzXmyGKz .disabled,#mermaid-svg-jvqjWPVhfzXmyGKz .disabled circle,#mermaid-svg-jvqjWPVhfzXmyGKz .disabled text{fill:lightgray;}#mermaid-svg-jvqjWPVhfzXmyGKz .disabled text{fill:#efefef;}#mermaid-svg-jvqjWPVhfzXmyGKz .section-8 rect,#mermaid-svg-jvqjWPVhfzXmyGKz .section-8 path,#mermaid-svg-jvqjWPVhfzXmyGKz .section-8 circle,#mermaid-svg-jvqjWPVhfzXmyGKz .section-8 polygon,#mermaid-svg-jvqjWPVhfzXmyGKz .section-8 path{fill:hsl(150, 100%, 76.2745098039%);}#mermaid-svg-jvqjWPVhfzXmyGKz .section-8 text{fill:black;}#mermaid-svg-jvqjWPVhfzXmyGKz .node-icon-8{font-size:40px;color:black;}#mermaid-svg-jvqjWPVhfzXmyGKz .section-edge-8{stroke:hsl(150, 100%, 76.2745098039%);}#mermaid-svg-jvqjWPVhfzXmyGKz .edge-depth-8{stroke-width:-10;}#mermaid-svg-jvqjWPVhfzXmyGKz .section-8 line{stroke:hsl(330, 100%, 86.2745098039%);stroke-width:3;}#mermaid-svg-jvqjWPVhfzXmyGKz .disabled,#mermaid-svg-jvqjWPVhfzXmyGKz .disabled circle,#mermaid-svg-jvqjWPVhfzXmyGKz .disabled text{fill:lightgray;}#mermaid-svg-jvqjWPVhfzXmyGKz .disabled text{fill:#efefef;}#mermaid-svg-jvqjWPVhfzXmyGKz .section-9 rect,#mermaid-svg-jvqjWPVhfzXmyGKz .section-9 path,#mermaid-svg-jvqjWPVhfzXmyGKz .section-9 circle,#mermaid-svg-jvqjWPVhfzXmyGKz .section-9 polygon,#mermaid-svg-jvqjWPVhfzXmyGKz .section-9 path{fill:hsl(180, 100%, 76.2745098039%);}#mermaid-svg-jvqjWPVhfzXmyGKz .section-9 text{fill:black;}#mermaid-svg-jvqjWPVhfzXmyGKz .node-icon-9{font-size:40px;color:black;}#mermaid-svg-jvqjWPVhfzXmyGKz .section-edge-9{stroke:hsl(180, 100%, 76.2745098039%);}#mermaid-svg-jvqjWPVhfzXmyGKz .edge-depth-9{stroke-width:-13;}#mermaid-svg-jvqjWPVhfzXmyGKz .section-9 line{stroke:hsl(0, 100%, 86.2745098039%);stroke-width:3;}#mermaid-svg-jvqjWPVhfzXmyGKz .disabled,#mermaid-svg-jvqjWPVhfzXmyGKz .disabled circle,#mermaid-svg-jvqjWPVhfzXmyGKz .disabled text{fill:lightgray;}#mermaid-svg-jvqjWPVhfzXmyGKz .disabled text{fill:#efefef;}#mermaid-svg-jvqjWPVhfzXmyGKz .section-10 rect,#mermaid-svg-jvqjWPVhfzXmyGKz .section-10 path,#mermaid-svg-jvqjWPVhfzXmyGKz .section-10 circle,#mermaid-svg-jvqjWPVhfzXmyGKz .section-10 polygon,#mermaid-svg-jvqjWPVhfzXmyGKz .section-10 path{fill:hsl(210, 100%, 76.2745098039%);}#mermaid-svg-jvqjWPVhfzXmyGKz .section-10 text{fill:black;}#mermaid-svg-jvqjWPVhfzXmyGKz .node-icon-10{font-size:40px;color:black;}#mermaid-svg-jvqjWPVhfzXmyGKz .section-edge-10{stroke:hsl(210, 100%, 76.2745098039%);}#mermaid-svg-jvqjWPVhfzXmyGKz .edge-depth-10{stroke-width:-16;}#mermaid-svg-jvqjWPVhfzXmyGKz .section-10 line{stroke:hsl(30, 100%, 86.2745098039%);stroke-width:3;}#mermaid-svg-jvqjWPVhfzXmyGKz .disabled,#mermaid-svg-jvqjWPVhfzXmyGKz .disabled circle,#mermaid-svg-jvqjWPVhfzXmyGKz .disabled text{fill:lightgray;}#mermaid-svg-jvqjWPVhfzXmyGKz .disabled text{fill:#efefef;}#mermaid-svg-jvqjWPVhfzXmyGKz .section-root rect,#mermaid-svg-jvqjWPVhfzXmyGKz .section-root path,#mermaid-svg-jvqjWPVhfzXmyGKz .section-root circle,#mermaid-svg-jvqjWPVhfzXmyGKz .section-root polygon{fill:hsl(240, 100%, 46.2745098039%);}#mermaid-svg-jvqjWPVhfzXmyGKz .section-root text{fill:#ffffff;}#mermaid-svg-jvqjWPVhfzXmyGKz .section-root span{color:#ffffff;}#mermaid-svg-jvqjWPVhfzXmyGKz .section-2 span{color:#ffffff;}#mermaid-svg-jvqjWPVhfzXmyGKz .icon-container{height:100%;display:flex;justify-content:center;align-items:center;}#mermaid-svg-jvqjWPVhfzXmyGKz .edge{fill:none;}#mermaid-svg-jvqjWPVhfzXmyGKz .mindmap-node-label{dy:1em;alignment-baseline:middle;text-anchor:middle;dominant-baseline:middle;text-align:center;}#mermaid-svg-jvqjWPVhfzXmyGKz :root{–mermaid-font-family:\”trebuchet ms\”,verdana,arial,sans-serif;}
Java线程同步
互斥锁
synchronized
synchronized方法
synchronized块
静态同步方法
ReentrantLock
公平锁/非公平锁
可中断锁
超时获取
条件变量
原子操作
AtomicInteger
AtomicLong
AtomicReference
LongAdder
信号量
Semaphore
CountDownLatch
CyclicBarrier
线程局部变量
ThreadLocal
其他工具
volatile
ReadWriteLock
StampedLock
5. synchronized:Java 最基础的同步机制
5.1 synchronized 的三种用法
public class SynchronizedDemo {
// 1. 修饰实例方法:锁的是当前实例对象
public synchronized void instanceMethod() {
// 同步代码
}
// 2. 修饰静态方法:锁的是类的 Class 对象
public static synchronized void staticMethod() {
// 同步代码
}
// 3. 修饰代码块:可以指定锁对象
public void blockMethod() {
synchronized(this) { // 锁当前实例
// 同步代码
}
synchronized(SynchronizedDemo.class) { // 锁 Class 对象
// 同步代码
}
private final Object lock = new Object();
synchronized(lock) { // 锁自定义对象
// 同步代码
}
}
}
5.2 锁的获取与释放流程
#mermaid-svg-LozIJ3ZyPH0iMEkO{font-family:\”trebuchet ms\”,verdana,arial,sans-serif;font-size:16px;fill:#333;}@keyframes edge-animation-frame{from{stroke-dashoffset:0;}}@keyframes dash{to{stroke-dashoffset:0;}}#mermaid-svg-LozIJ3ZyPH0iMEkO .edge-animation-slow{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 50s linear infinite;stroke-linecap:round;}#mermaid-svg-LozIJ3ZyPH0iMEkO .edge-animation-fast{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 20s linear infinite;stroke-linecap:round;}#mermaid-svg-LozIJ3ZyPH0iMEkO .error-icon{fill:#552222;}#mermaid-svg-LozIJ3ZyPH0iMEkO .error-text{fill:#552222;stroke:#552222;}#mermaid-svg-LozIJ3ZyPH0iMEkO .edge-thickness-normal{stroke-width:1px;}#mermaid-svg-LozIJ3ZyPH0iMEkO .edge-thickness-thick{stroke-width:3.5px;}#mermaid-svg-LozIJ3ZyPH0iMEkO .edge-pattern-solid{stroke-dasharray:0;}#mermaid-svg-LozIJ3ZyPH0iMEkO .edge-thickness-invisible{stroke-width:0;fill:none;}#mermaid-svg-LozIJ3ZyPH0iMEkO .edge-pattern-dashed{stroke-dasharray:3;}#mermaid-svg-LozIJ3ZyPH0iMEkO .edge-pattern-dotted{stroke-dasharray:2;}#mermaid-svg-LozIJ3ZyPH0iMEkO .marker{fill:#333333;stroke:#333333;}#mermaid-svg-LozIJ3ZyPH0iMEkO .marker.cross{stroke:#333333;}#mermaid-svg-LozIJ3ZyPH0iMEkO svg{font-family:\”trebuchet ms\”,verdana,arial,sans-serif;font-size:16px;}#mermaid-svg-LozIJ3ZyPH0iMEkO p{margin:0;}#mermaid-svg-LozIJ3ZyPH0iMEkO .label{font-family:\”trebuchet ms\”,verdana,arial,sans-serif;color:#333;}#mermaid-svg-LozIJ3ZyPH0iMEkO .cluster-label text{fill:#333;}#mermaid-svg-LozIJ3ZyPH0iMEkO .cluster-label span{color:#333;}#mermaid-svg-LozIJ3ZyPH0iMEkO .cluster-label span p{background-color:transparent;}#mermaid-svg-LozIJ3ZyPH0iMEkO .label text,#mermaid-svg-LozIJ3ZyPH0iMEkO span{fill:#333;color:#333;}#mermaid-svg-LozIJ3ZyPH0iMEkO .node rect,#mermaid-svg-LozIJ3ZyPH0iMEkO .node circle,#mermaid-svg-LozIJ3ZyPH0iMEkO .node ellipse,#mermaid-svg-LozIJ3ZyPH0iMEkO .node polygon,#mermaid-svg-LozIJ3ZyPH0iMEkO .node path{fill:#ECECFF;stroke:#9370DB;stroke-width:1px;}#mermaid-svg-LozIJ3ZyPH0iMEkO .rough-node .label text,#mermaid-svg-LozIJ3ZyPH0iMEkO .node .label text,#mermaid-svg-LozIJ3ZyPH0iMEkO .image-shape .label,#mermaid-svg-LozIJ3ZyPH0iMEkO .icon-shape .label{text-anchor:middle;}#mermaid-svg-LozIJ3ZyPH0iMEkO .node .katex path{fill:#000;stroke:#000;stroke-width:1px;}#mermaid-svg-LozIJ3ZyPH0iMEkO .rough-node .label,#mermaid-svg-LozIJ3ZyPH0iMEkO .node .label,#mermaid-svg-LozIJ3ZyPH0iMEkO .image-shape .label,#mermaid-svg-LozIJ3ZyPH0iMEkO .icon-shape .label{text-align:center;}#mermaid-svg-LozIJ3ZyPH0iMEkO .node.clickable{cursor:pointer;}#mermaid-svg-LozIJ3ZyPH0iMEkO .root .anchor path{fill:#333333!important;stroke-width:0;stroke:#333333;}#mermaid-svg-LozIJ3ZyPH0iMEkO .arrowheadPath{fill:#333333;}#mermaid-svg-LozIJ3ZyPH0iMEkO .edgePath .path{stroke:#333333;stroke-width:2.0px;}#mermaid-svg-LozIJ3ZyPH0iMEkO .flowchart-link{stroke:#333333;fill:none;}#mermaid-svg-LozIJ3ZyPH0iMEkO .edgeLabel{background-color:rgba(232,232,232, 0.8);text-align:center;}#mermaid-svg-LozIJ3ZyPH0iMEkO .edgeLabel p{background-color:rgba(232,232,232, 0.8);}#mermaid-svg-LozIJ3ZyPH0iMEkO .edgeLabel rect{opacity:0.5;background-color:rgba(232,232,232, 0.8);fill:rgba(232,232,232, 0.8);}#mermaid-svg-LozIJ3ZyPH0iMEkO .labelBkg{background-color:rgba(232, 232, 232, 0.5);}#mermaid-svg-LozIJ3ZyPH0iMEkO .cluster rect{fill:#ffffde;stroke:#aaaa33;stroke-width:1px;}#mermaid-svg-LozIJ3ZyPH0iMEkO .cluster text{fill:#333;}#mermaid-svg-LozIJ3ZyPH0iMEkO .cluster span{color:#333;}#mermaid-svg-LozIJ3ZyPH0iMEkO div.mermaidTooltip{position:absolute;text-align:center;max-width:200px;padding:2px;font-family:\”trebuchet ms\”,verdana,arial,sans-serif;font-size:12px;background:hsl(80, 100%, 96.2745098039%);border:1px solid #aaaa33;border-radius:2px;pointer-events:none;z-index:100;}#mermaid-svg-LozIJ3ZyPH0iMEkO .flowchartTitleText{text-anchor:middle;font-size:18px;fill:#333;}#mermaid-svg-LozIJ3ZyPH0iMEkO rect.text{fill:none;stroke-width:0;}#mermaid-svg-LozIJ3ZyPH0iMEkO .icon-shape,#mermaid-svg-LozIJ3ZyPH0iMEkO .image-shape{background-color:rgba(232,232,232, 0.8);text-align:center;}#mermaid-svg-LozIJ3ZyPH0iMEkO .icon-shape p,#mermaid-svg-LozIJ3ZyPH0iMEkO .image-shape p{background-color:rgba(232,232,232, 0.8);padding:2px;}#mermaid-svg-LozIJ3ZyPH0iMEkO .icon-shape .label rect,#mermaid-svg-LozIJ3ZyPH0iMEkO .image-shape .label rect{opacity:0.5;background-color:rgba(232,232,232, 0.8);fill:rgba(232,232,232, 0.8);}#mermaid-svg-LozIJ3ZyPH0iMEkO .label-icon{display:inline-block;height:1em;overflow:visible;vertical-align:-0.125em;}#mermaid-svg-LozIJ3ZyPH0iMEkO .node .label-icon path{fill:currentColor;stroke:revert;stroke-width:revert;}#mermaid-svg-LozIJ3ZyPH0iMEkO :root{–mermaid-font-family:\”trebuchet ms\”,verdana,arial,sans-serif;}
是
否
锁升级过程
无锁
偏向锁
轻量级锁
重量级锁
线程尝试获取锁
锁是否可用?
线程获得锁
执行同步代码块
释放锁
其他线程可获取
线程进入阻塞队列
等待锁释放
被唤醒
5.3 解决之前的计数器问题
public class SafeCounter {
private int count = 0;
// 加上 synchronized 即可解决
public synchronized void increment() {
count++;
}
public synchronized int getCount() {
return count;
}
// 或者使用同步块,更精细的控制
private final Object lock = new Object();
public void increment2() {
synchronized(lock) {
count++;
}
}
}
6. ReentrantLock:更灵活的锁
6.1 基本用法
public class ReentrantLockDemo {
private final ReentrantLock lock = new ReentrantLock(); // 非公平锁(默认)
private final ReentrantLock fairLock = new ReentrantLock(true); // 公平锁
private int count = 0;
public void increment() {
lock.lock(); // 获取锁
try {
count++;
} finally {
lock.unlock(); // 务必在 finally 中释放
}
}
// 尝试获取锁(非阻塞)
public boolean tryIncrement() {
if (lock.tryLock()) {
try {
count++;
return true;
} finally {
lock.unlock();
}
}
return false;
}
// 尝试获取锁(带超时)
public boolean tryIncrementWithTimeout() throws InterruptedException {
if (lock.tryLock(1, TimeUnit.SECONDS)) {
try {
count++;
return true;
} finally {
lock.unlock();
}
}
return false;
}
}
6.2 synchronized vs ReentrantLock
| 获取锁方式 | 隐式 | 显式 lock()/unlock() |
| 可中断性 | 不支持 | 支持 lockInterruptibly() |
| 超时获取 | 不支持 | 支持 tryLock(timeout) |
| 公平锁 | 非公平 | 可设置公平/非公平 |
| 条件变量 | wait/notify | Condition (多个) |
| 锁绑定多个条件 | 一个 | 多个 |
| 性能 | 已优化,接近 | 略高 |
| 使用复杂度 | 简单 | 较复杂 |
7. 原子类:无锁同步
7.1 原子类的原理
原子类基于 CAS (Compare-And-Swap) 实现,是一种乐观锁机制。
#mermaid-svg-jEW97U71dLIA3n9b{font-family:\”trebuchet ms\”,verdana,arial,sans-serif;font-size:16px;fill:#333;}@keyframes edge-animation-frame{from{stroke-dashoffset:0;}}@keyframes dash{to{stroke-dashoffset:0;}}#mermaid-svg-jEW97U71dLIA3n9b .edge-animation-slow{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 50s linear infinite;stroke-linecap:round;}#mermaid-svg-jEW97U71dLIA3n9b .edge-animation-fast{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 20s linear infinite;stroke-linecap:round;}#mermaid-svg-jEW97U71dLIA3n9b .error-icon{fill:#552222;}#mermaid-svg-jEW97U71dLIA3n9b .error-text{fill:#552222;stroke:#552222;}#mermaid-svg-jEW97U71dLIA3n9b .edge-thickness-normal{stroke-width:1px;}#mermaid-svg-jEW97U71dLIA3n9b .edge-thickness-thick{stroke-width:3.5px;}#mermaid-svg-jEW97U71dLIA3n9b .edge-pattern-solid{stroke-dasharray:0;}#mermaid-svg-jEW97U71dLIA3n9b .edge-thickness-invisible{stroke-width:0;fill:none;}#mermaid-svg-jEW97U71dLIA3n9b .edge-pattern-dashed{stroke-dasharray:3;}#mermaid-svg-jEW97U71dLIA3n9b .edge-pattern-dotted{stroke-dasharray:2;}#mermaid-svg-jEW97U71dLIA3n9b .marker{fill:#333333;stroke:#333333;}#mermaid-svg-jEW97U71dLIA3n9b .marker.cross{stroke:#333333;}#mermaid-svg-jEW97U71dLIA3n9b svg{font-family:\”trebuchet ms\”,verdana,arial,sans-serif;font-size:16px;}#mermaid-svg-jEW97U71dLIA3n9b p{margin:0;}#mermaid-svg-jEW97U71dLIA3n9b .label{font-family:\”trebuchet ms\”,verdana,arial,sans-serif;color:#333;}#mermaid-svg-jEW97U71dLIA3n9b .cluster-label text{fill:#333;}#mermaid-svg-jEW97U71dLIA3n9b .cluster-label span{color:#333;}#mermaid-svg-jEW97U71dLIA3n9b .cluster-label span p{background-color:transparent;}#mermaid-svg-jEW97U71dLIA3n9b .label text,#mermaid-svg-jEW97U71dLIA3n9b span{fill:#333;color:#333;}#mermaid-svg-jEW97U71dLIA3n9b .node rect,#mermaid-svg-jEW97U71dLIA3n9b .node circle,#mermaid-svg-jEW97U71dLIA3n9b .node ellipse,#mermaid-svg-jEW97U71dLIA3n9b .node polygon,#mermaid-svg-jEW97U71dLIA3n9b .node path{fill:#ECECFF;stroke:#9370DB;stroke-width:1px;}#mermaid-svg-jEW97U71dLIA3n9b .rough-node .label text,#mermaid-svg-jEW97U71dLIA3n9b .node .label text,#mermaid-svg-jEW97U71dLIA3n9b .image-shape .label,#mermaid-svg-jEW97U71dLIA3n9b .icon-shape .label{text-anchor:middle;}#mermaid-svg-jEW97U71dLIA3n9b .node .katex path{fill:#000;stroke:#000;stroke-width:1px;}#mermaid-svg-jEW97U71dLIA3n9b .rough-node .label,#mermaid-svg-jEW97U71dLIA3n9b .node .label,#mermaid-svg-jEW97U71dLIA3n9b .image-shape .label,#mermaid-svg-jEW97U71dLIA3n9b .icon-shape .label{text-align:center;}#mermaid-svg-jEW97U71dLIA3n9b .node.clickable{cursor:pointer;}#mermaid-svg-jEW97U71dLIA3n9b .root .anchor path{fill:#333333!important;stroke-width:0;stroke:#333333;}#mermaid-svg-jEW97U71dLIA3n9b .arrowheadPath{fill:#333333;}#mermaid-svg-jEW97U71dLIA3n9b .edgePath .path{stroke:#333333;stroke-width:2.0px;}#mermaid-svg-jEW97U71dLIA3n9b .flowchart-link{stroke:#333333;fill:none;}#mermaid-svg-jEW97U71dLIA3n9b .edgeLabel{background-color:rgba(232,232,232, 0.8);text-align:center;}#mermaid-svg-jEW97U71dLIA3n9b .edgeLabel p{background-color:rgba(232,232,232, 0.8);}#mermaid-svg-jEW97U71dLIA3n9b .edgeLabel rect{opacity:0.5;background-color:rgba(232,232,232, 0.8);fill:rgba(232,232,232, 0.8);}#mermaid-svg-jEW97U71dLIA3n9b .labelBkg{background-color:rgba(232, 232, 232, 0.5);}#mermaid-svg-jEW97U71dLIA3n9b .cluster rect{fill:#ffffde;stroke:#aaaa33;stroke-width:1px;}#mermaid-svg-jEW97U71dLIA3n9b .cluster text{fill:#333;}#mermaid-svg-jEW97U71dLIA3n9b .cluster span{color:#333;}#mermaid-svg-jEW97U71dLIA3n9b div.mermaidTooltip{position:absolute;text-align:center;max-width:200px;padding:2px;font-family:\”trebuchet ms\”,verdana,arial,sans-serif;font-size:12px;background:hsl(80, 100%, 96.2745098039%);border:1px solid #aaaa33;border-radius:2px;pointer-events:none;z-index:100;}#mermaid-svg-jEW97U71dLIA3n9b .flowchartTitleText{text-anchor:middle;font-size:18px;fill:#333;}#mermaid-svg-jEW97U71dLIA3n9b rect.text{fill:none;stroke-width:0;}#mermaid-svg-jEW97U71dLIA3n9b .icon-shape,#mermaid-svg-jEW97U71dLIA3n9b .image-shape{background-color:rgba(232,232,232, 0.8);text-align:center;}#mermaid-svg-jEW97U71dLIA3n9b .icon-shape p,#mermaid-svg-jEW97U71dLIA3n9b .image-shape p{background-color:rgba(232,232,232, 0.8);padding:2px;}#mermaid-svg-jEW97U71dLIA3n9b .icon-shape .label rect,#mermaid-svg-jEW97U71dLIA3n9b .image-shape .label rect{opacity:0.5;background-color:rgba(232,232,232, 0.8);fill:rgba(232,232,232, 0.8);}#mermaid-svg-jEW97U71dLIA3n9b .label-icon{display:inline-block;height:1em;overflow:visible;vertical-align:-0.125em;}#mermaid-svg-jEW97U71dLIA3n9b .node .label-icon path{fill:currentColor;stroke:revert;stroke-width:revert;}#mermaid-svg-jEW97U71dLIA3n9b :root{–mermaid-font-family:\”trebuchet ms\”,verdana,arial,sans-serif;}
是
否
读取当前值 V
计算新值
CAS 操作内存值是否仍为 V?
更新为新值
重试/失败
7.2 原子类示例
public class AtomicCounter {
private final AtomicInteger count = new AtomicInteger(0);
public void increment() {
count.incrementAndGet(); // 原子操作,无需锁
}
public int getCount() {
return count.get();
}
// 更复杂的原子操作
public void updateIfCondition() {
count.updateAndGet(x -> {
if (x < 100) return x + 1;
return x;
});
}
public static void main(String[] args) throws InterruptedException {
AtomicCounter counter = new AtomicCounter();
// 多线程测试,结果正确
}
}
7.3 常用原子类对比
| AtomicInteger | int 类型 | 最常用 |
| AtomicLong | long 类型 | 支持 64 位原子操作 |
| AtomicBoolean | boolean 类型 | 简洁 |
| AtomicReference | 引用类型 | 可原子更新对象引用 |
| AtomicIntegerArray | int 数组 | 数组元素的原子操作 |
| LongAdder | 高并发计数 | 分段累加,性能优于 AtomicLong |
| AtomicReferenceFieldUpdater | 字段更新器 | 原子更新 volatile 字段 |
8. 条件变量:线程间的协作
8.1 wait/notify 机制
生产者线程
共享队列
消费者线程
生产者线程
共享队列
消费者线程
#mermaid-svg-w2SJGio1bjmqGk84{font-family:\”trebuchet ms\”,verdana,arial,sans-serif;font-size:16px;fill:#333;}@keyframes edge-animation-frame{from{stroke-dashoffset:0;}}@keyframes dash{to{stroke-dashoffset:0;}}#mermaid-svg-w2SJGio1bjmqGk84 .edge-animation-slow{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 50s linear infinite;stroke-linecap:round;}#mermaid-svg-w2SJGio1bjmqGk84 .edge-animation-fast{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 20s linear infinite;stroke-linecap:round;}#mermaid-svg-w2SJGio1bjmqGk84 .error-icon{fill:#552222;}#mermaid-svg-w2SJGio1bjmqGk84 .error-text{fill:#552222;stroke:#552222;}#mermaid-svg-w2SJGio1bjmqGk84 .edge-thickness-normal{stroke-width:1px;}#mermaid-svg-w2SJGio1bjmqGk84 .edge-thickness-thick{stroke-width:3.5px;}#mermaid-svg-w2SJGio1bjmqGk84 .edge-pattern-solid{stroke-dasharray:0;}#mermaid-svg-w2SJGio1bjmqGk84 .edge-thickness-invisible{stroke-width:0;fill:none;}#mermaid-svg-w2SJGio1bjmqGk84 .edge-pattern-dashed{stroke-dasharray:3;}#mermaid-svg-w2SJGio1bjmqGk84 .edge-pattern-dotted{stroke-dasharray:2;}#mermaid-svg-w2SJGio1bjmqGk84 .marker{fill:#333333;stroke:#333333;}#mermaid-svg-w2SJGio1bjmqGk84 .marker.cross{stroke:#333333;}#mermaid-svg-w2SJGio1bjmqGk84 svg{font-family:\”trebuchet ms\”,verdana,arial,sans-serif;font-size:16px;}#mermaid-svg-w2SJGio1bjmqGk84 p{margin:0;}#mermaid-svg-w2SJGio1bjmqGk84 .actor{stroke:hsl(259.6261682243, 59.7765363128%, 87.9019607843%);fill:#ECECFF;}#mermaid-svg-w2SJGio1bjmqGk84 text.actor>tspan{fill:black;stroke:none;}#mermaid-svg-w2SJGio1bjmqGk84 .actor-line{stroke:hsl(259.6261682243, 59.7765363128%, 87.9019607843%);}#mermaid-svg-w2SJGio1bjmqGk84 .innerArc{stroke-width:1.5;stroke-dasharray:none;}#mermaid-svg-w2SJGio1bjmqGk84 .messageLine0{stroke-width:1.5;stroke-dasharray:none;stroke:#333;}#mermaid-svg-w2SJGio1bjmqGk84 .messageLine1{stroke-width:1.5;stroke-dasharray:2,2;stroke:#333;}#mermaid-svg-w2SJGio1bjmqGk84 #arrowhead path{fill:#333;stroke:#333;}#mermaid-svg-w2SJGio1bjmqGk84 .sequenceNumber{fill:white;}#mermaid-svg-w2SJGio1bjmqGk84 #sequencenumber{fill:#333;}#mermaid-svg-w2SJGio1bjmqGk84 #crosshead path{fill:#333;stroke:#333;}#mermaid-svg-w2SJGio1bjmqGk84 .messageText{fill:#333;stroke:none;}#mermaid-svg-w2SJGio1bjmqGk84 .labelBox{stroke:hsl(259.6261682243, 59.7765363128%, 87.9019607843%);fill:#ECECFF;}#mermaid-svg-w2SJGio1bjmqGk84 .labelText,#mermaid-svg-w2SJGio1bjmqGk84 .labelText>tspan{fill:black;stroke:none;}#mermaid-svg-w2SJGio1bjmqGk84 .loopText,#mermaid-svg-w2SJGio1bjmqGk84 .loopText>tspan{fill:black;stroke:none;}#mermaid-svg-w2SJGio1bjmqGk84 .loopLine{stroke-width:2px;stroke-dasharray:2,2;stroke:hsl(259.6261682243, 59.7765363128%, 87.9019607843%);fill:hsl(259.6261682243, 59.7765363128%, 87.9019607843%);}#mermaid-svg-w2SJGio1bjmqGk84 .note{stroke:#aaaa33;fill:#fff5ad;}#mermaid-svg-w2SJGio1bjmqGk84 .noteText,#mermaid-svg-w2SJGio1bjmqGk84 .noteText>tspan{fill:black;stroke:none;}#mermaid-svg-w2SJGio1bjmqGk84 .activation0{fill:#f4f4f4;stroke:#666;}#mermaid-svg-w2SJGio1bjmqGk84 .activation1{fill:#f4f4f4;stroke:#666;}#mermaid-svg-w2SJGio1bjmqGk84 .activation2{fill:#f4f4f4;stroke:#666;}#mermaid-svg-w2SJGio1bjmqGk84 .actorPopupMenu{position:absolute;}#mermaid-svg-w2SJGio1bjmqGk84 .actorPopupMenuPanel{position:absolute;fill:#ECECFF;box-shadow:0px 8px 16px 0px rgba(0,0,0,0.2);filter:drop-shadow(3px 5px 2px rgb(0 0 0 / 0.4));}#mermaid-svg-w2SJGio1bjmqGk84 .actor-man line{stroke:hsl(259.6261682243, 59.7765363128%, 87.9019607843%);fill:#ECECFF;}#mermaid-svg-w2SJGio1bjmqGk84 .actor-man circle,#mermaid-svg-w2SJGio1bjmqGk84 line{stroke:hsl(259.6261682243, 59.7765363128%, 87.9019607843%);fill:#ECECFF;stroke-width:2px;}#mermaid-svg-w2SJGio1bjmqGk84 :root{–mermaid-font-family:\”trebuchet ms\”,verdana,arial,sans-serif;}
发现队列为空
wait() 进入等待
生产数据
notifyAll()
唤醒
消费数据
public class ProducerConsumerDemo {
private final Queue<Integer> queue = new LinkedList<>();
private final int MAX_SIZE = 10;
// 生产者
public synchronized void produce() throws InterruptedException {
while (queue.size() == MAX_SIZE) {
wait(); // 队列满,等待
}
queue.offer(1);
notifyAll(); // 唤醒消费者
}
// 消费者
public synchronized void consume() throws InterruptedException {
while (queue.isEmpty()) {
wait(); // 队列空,等待
}
queue.poll();
notifyAll(); // 唤醒生产者
}
}
8.2 Condition 接口(ReentrantLock)
public class ConditionDemo {
private final ReentrantLock lock = new ReentrantLock();
private final Condition notFull = lock.newCondition();
private final Condition notEmpty = lock.newCondition();
private final Queue<Integer> queue = new LinkedList<>();
private final int MAX_SIZE = 10;
public void produce() throws InterruptedException {
lock.lock();
try {
while (queue.size() == MAX_SIZE) {
notFull.await(); // 等待队列不满
}
queue.offer(1);
notEmpty.signal(); // 通知队列不空
} finally {
lock.unlock();
}
}
public void consume() throws InterruptedException {
lock.lock();
try {
while (queue.isEmpty()) {
notEmpty.await(); // 等待队列不空
}
queue.poll();
notFull.signal(); // 通知队列不满
} finally {
lock.unlock();
}
}
}
9. 其他同步工具
9.1 volatile:轻量级同步
public class VolatileDemo {
private volatile boolean flag = true; // volatile 保证可见性
private int value = 0; // 普通变量
public void writer() {
value = 42; // 普通写
flag = false; // volatile 写,会触发内存屏障
}
public void reader() {
if (flag) { // volatile 读
System.out.println(value); // 能保证看到 42
}
}
}
volatile 的语义:
- 可见性:对一个 volatile 变量的写,立即对其他线程可见
- 禁止指令重排序:volatile 写之前的操作不会重排序到之后
- 不保证原子性:volatile count++ 仍然是线程不安全的
9.2 ThreadLocal:线程隔离
public class ThreadLocalDemo {
// 每个线程都有自己的 SimpleDateFormat 实例
private static final ThreadLocal<SimpleDateFormat> dateFormat =
ThreadLocal.withInitial(() -> new SimpleDateFormat("yyyy-MM-dd"));
public String formatDate(Date date) {
return dateFormat.get().format(date);
}
// 使用后记得清理,避免内存泄漏
public void cleanup() {
dateFormat.remove();
}
}
10. 同步策略选择指南
#mermaid-svg-gIIswosA6EdjvHe8{font-family:\”trebuchet ms\”,verdana,arial,sans-serif;font-size:16px;fill:#333;}@keyframes edge-animation-frame{from{stroke-dashoffset:0;}}@keyframes dash{to{stroke-dashoffset:0;}}#mermaid-svg-gIIswosA6EdjvHe8 .edge-animation-slow{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 50s linear infinite;stroke-linecap:round;}#mermaid-svg-gIIswosA6EdjvHe8 .edge-animation-fast{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 20s linear infinite;stroke-linecap:round;}#mermaid-svg-gIIswosA6EdjvHe8 .error-icon{fill:#552222;}#mermaid-svg-gIIswosA6EdjvHe8 .error-text{fill:#552222;stroke:#552222;}#mermaid-svg-gIIswosA6EdjvHe8 .edge-thickness-normal{stroke-width:1px;}#mermaid-svg-gIIswosA6EdjvHe8 .edge-thickness-thick{stroke-width:3.5px;}#mermaid-svg-gIIswosA6EdjvHe8 .edge-pattern-solid{stroke-dasharray:0;}#mermaid-svg-gIIswosA6EdjvHe8 .edge-thickness-invisible{stroke-width:0;fill:none;}#mermaid-svg-gIIswosA6EdjvHe8 .edge-pattern-dashed{stroke-dasharray:3;}#mermaid-svg-gIIswosA6EdjvHe8 .edge-pattern-dotted{stroke-dasharray:2;}#mermaid-svg-gIIswosA6EdjvHe8 .marker{fill:#333333;stroke:#333333;}#mermaid-svg-gIIswosA6EdjvHe8 .marker.cross{stroke:#333333;}#mermaid-svg-gIIswosA6EdjvHe8 svg{font-family:\”trebuchet ms\”,verdana,arial,sans-serif;font-size:16px;}#mermaid-svg-gIIswosA6EdjvHe8 p{margin:0;}#mermaid-svg-gIIswosA6EdjvHe8 .label{font-family:\”trebuchet ms\”,verdana,arial,sans-serif;color:#333;}#mermaid-svg-gIIswosA6EdjvHe8 .cluster-label text{fill:#333;}#mermaid-svg-gIIswosA6EdjvHe8 .cluster-label span{color:#333;}#mermaid-svg-gIIswosA6EdjvHe8 .cluster-label span p{background-color:transparent;}#mermaid-svg-gIIswosA6EdjvHe8 .label text,#mermaid-svg-gIIswosA6EdjvHe8 span{fill:#333;color:#333;}#mermaid-svg-gIIswosA6EdjvHe8 .node rect,#mermaid-svg-gIIswosA6EdjvHe8 .node circle,#mermaid-svg-gIIswosA6EdjvHe8 .node ellipse,#mermaid-svg-gIIswosA6EdjvHe8 .node polygon,#mermaid-svg-gIIswosA6EdjvHe8 .node path{fill:#ECECFF;stroke:#9370DB;stroke-width:1px;}#mermaid-svg-gIIswosA6EdjvHe8 .rough-node .label text,#mermaid-svg-gIIswosA6EdjvHe8 .node .label text,#mermaid-svg-gIIswosA6EdjvHe8 .image-shape .label,#mermaid-svg-gIIswosA6EdjvHe8 .icon-shape .label{text-anchor:middle;}#mermaid-svg-gIIswosA6EdjvHe8 .node .katex path{fill:#000;stroke:#000;stroke-width:1px;}#mermaid-svg-gIIswosA6EdjvHe8 .rough-node .label,#mermaid-svg-gIIswosA6EdjvHe8 .node .label,#mermaid-svg-gIIswosA6EdjvHe8 .image-shape .label,#mermaid-svg-gIIswosA6EdjvHe8 .icon-shape .label{text-align:center;}#mermaid-svg-gIIswosA6EdjvHe8 .node.clickable{cursor:pointer;}#mermaid-svg-gIIswosA6EdjvHe8 .root .anchor path{fill:#333333!important;stroke-width:0;stroke:#333333;}#mermaid-svg-gIIswosA6EdjvHe8 .arrowheadPath{fill:#333333;}#mermaid-svg-gIIswosA6EdjvHe8 .edgePath .path{stroke:#333333;stroke-width:2.0px;}#mermaid-svg-gIIswosA6EdjvHe8 .flowchart-link{stroke:#333333;fill:none;}#mermaid-svg-gIIswosA6EdjvHe8 .edgeLabel{background-color:rgba(232,232,232, 0.8);text-align:center;}#mermaid-svg-gIIswosA6EdjvHe8 .edgeLabel p{background-color:rgba(232,232,232, 0.8);}#mermaid-svg-gIIswosA6EdjvHe8 .edgeLabel rect{opacity:0.5;background-color:rgba(232,232,232, 0.8);fill:rgba(232,232,232, 0.8);}#mermaid-svg-gIIswosA6EdjvHe8 .labelBkg{background-color:rgba(232, 232, 232, 0.5);}#mermaid-svg-gIIswosA6EdjvHe8 .cluster rect{fill:#ffffde;stroke:#aaaa33;stroke-width:1px;}#mermaid-svg-gIIswosA6EdjvHe8 .cluster text{fill:#333;}#mermaid-svg-gIIswosA6EdjvHe8 .cluster span{color:#333;}#mermaid-svg-gIIswosA6EdjvHe8 div.mermaidTooltip{position:absolute;text-align:center;max-width:200px;padding:2px;font-family:\”trebuchet ms\”,verdana,arial,sans-serif;font-size:12px;background:hsl(80, 100%, 96.2745098039%);border:1px solid #aaaa33;border-radius:2px;pointer-events:none;z-index:100;}#mermaid-svg-gIIswosA6EdjvHe8 .flowchartTitleText{text-anchor:middle;font-size:18px;fill:#333;}#mermaid-svg-gIIswosA6EdjvHe8 rect.text{fill:none;stroke-width:0;}#mermaid-svg-gIIswosA6EdjvHe8 .icon-shape,#mermaid-svg-gIIswosA6EdjvHe8 .image-shape{background-color:rgba(232,232,232, 0.8);text-align:center;}#mermaid-svg-gIIswosA6EdjvHe8 .icon-shape p,#mermaid-svg-gIIswosA6EdjvHe8 .image-shape p{background-color:rgba(232,232,232, 0.8);padding:2px;}#mermaid-svg-gIIswosA6EdjvHe8 .icon-shape .label rect,#mermaid-svg-gIIswosA6EdjvHe8 .image-shape .label rect{opacity:0.5;background-color:rgba(232,232,232, 0.8);fill:rgba(232,232,232, 0.8);}#mermaid-svg-gIIswosA6EdjvHe8 .label-icon{display:inline-block;height:1em;overflow:visible;vertical-align:-0.125em;}#mermaid-svg-gIIswosA6EdjvHe8 .node .label-icon path{fill:currentColor;stroke:revert;stroke-width:revert;}#mermaid-svg-gIIswosA6EdjvHe8 :root{–mermaid-font-family:\”trebuchet ms\”,verdana,arial,sans-serif;}
简单计数
只有一个共享变量
复杂共享状态
简单易用
需要可中断/超时
读多写少
高性能读写
需要线程同步
共享资源的特征?
AtomicLong/LongAdder
volatile + CAS
需要什么特性?
synchronized
ReentrantLock
ReadWriteLock
StampedLock
推荐
10.1 选择决策表
| 简单计数器 | AtomicInteger/LongAdder | 无锁,高性能 |
| 代码块互斥 | synchronized | 简单,足够用 |
| 需要尝试获取锁 | ReentrantLock | 支持 tryLock |
| 需要条件等待 | Condition | 更灵活 |
| 读远多于写 | ReadWriteLock | 读锁可并发 |
| 单变量标志位 | volatile | 最轻量 |
| 线程私有数据 | ThreadLocal | 无需同步 |
| 高并发计数 | LongAdder | 分段累加 |
11. 常见问题与最佳实践
11.1 死锁及其避免
// ❌ 死锁示例
public class DeadlockDemo {
private final Object lock1 = new Object();
private final Object lock2 = new Object();
public void method1() {
synchronized(lock1) {
synchronized(lock2) {
// 业务逻辑
}
}
}
public void method2() {
synchronized(lock2) { // 相反的加锁顺序
synchronized(lock1) {
// 业务逻辑
}
}
}
}
避免死锁的原则:
11.2 锁粒度控制
public class LockGranularity {
private final List<String> list = new ArrayList<>();
private final Map<String, Integer> map = new HashMap<>();
// ❌ 粗粒度锁:锁了整个对象
public synchronized void addBad(String key, String value) {
list.add(value);
map.put(key, value.length());
}
// ✅ 细粒度锁:使用不同的锁对象
private final Object listLock = new Object();
private final Object mapLock = new Object();
public void addGood(String key, String value) {
synchronized(listLock) {
list.add(value);
}
synchronized(mapLock) {
map.put(key, value.length());
}
}
}
11.3 最小化同步块
public class SyncMinimize {
private final List<String> data = new ArrayList<>();
// ❌ 整个方法同步
public synchronized void addBad(String item) {
// 耗时操作也在锁内
validateItem(item);
processItem(item);
data.add(item);
}
// ✅ 只同步必要的代码
public void addGood(String item) {
// 耗时操作在锁外
validateItem(item);
String processed = processItem(item);
// 只同步关键操作
synchronized(this) {
data.add(processed);
}
}
}
12. 总结
| synchronized | 通用互斥 | 简单、可靠 | 功能有限 |
| ReentrantLock | 需要高级锁功能 | 灵活、可中断 | 使用复杂 |
| volatile | 标志位、状态标识 | 轻量 | 不保证原子性 |
| 原子类 | 计数器、累加器 | 无锁、高性能 | 只支持简单类型 |
| ThreadLocal | 线程隔离数据 | 无竞争 | 内存需注意 |
| ReadWriteLock | 读多写少 | 读写分离 | 写操作互斥 |
| 信号量 | 资源池控制 | 可控制并发数 | 需手动释放 |
一句话总结:
线程同步是多线程编程的基石,Java 提供了从 synchronized 到 ReentrantLock、从 volatile 到 Atomic 类的多层次同步机制。选择合适的同步方案需要权衡性能、安全性和代码复杂度,核心原则是:只同步必要的代码,最小化锁持有时间,避免死锁和锁竞争。
📌 记住:同步不是万能的,过度同步会导致性能下降甚至死锁;设计之初就考虑线程安全性,比后期调试要重要得多。
如果觉得本文对你有帮助,欢迎点赞、收藏、转发~

|
🌺The End🌺点点关注,收藏不迷路🌺 |


