多线程进阶
多线程进阶
1. 常见锁策略
2. synchronized 优化策略
1. 锁升级
2. 锁消除
3. 锁粗化
3. CAS 指令
1. 什么是 CAS ?
一条 cpu 指令, CAS (M,A,B) -> *M = *A -> swap (M,B)
2. CAS 用处 ?
基于CAS实现 AtomicInteger 原子类
加锁 -> 通过阻塞, 保证结果正确
CAS -> 通过重试判断, oldvalue != value 说明有别的线程修改了value -> oldvalue = value -> swap(value, oldvalue+1)
AtomicInteger类 使用例子:
查看代码
import java.util.concurrent.atomic.AtomicInteger;
class Demo29 {
public static AtomicInteger count = new AtomicInteger(0);
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread(() -> {
for (int i = 0; i < 50000; i++) {
// count++;
count.getAndIncrement();
// ++ count;
// count.incrementAndGet();
// count--
// count.getAndDecrement();
// --count
// count.decrementAndGet();
}
});
Thread t2 = new Thread(() -> {
for (int i = 0; i < 50000; i++) {
count.getAndIncrement();
}
});
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println(count.get());
}
}
CAS 实现 自旋锁