CAS是什么
CAS实现类
引用类型原子类:
- AtomicReference(引用类型原子类)
- AtomicStampedRerence(携带版本号,可以解决CAS中ABA问题)
- AtomicMarkableReference(原子更新带有标记位的引用类型)
基础原子类:
- AtomicBoolean
- AtomicInteger
- AtomicLong
原子数组类:
- AtomicLongArray
- AtomicReferenceArray
原子方式更新对象中的字段类:
- AtomicIntegerFieldUpdate
- AtomicReferenceFieldUpdate
高并发汇总类:
- LongAdder
- LongAccumulator
- DoubleAdder
- DoubleAccumulator
synchronized加锁实例
```java public class TestAccount { public static void main(String[] args) {
} }Account account = new AccountUnsafe(10000);
Account.demo(account);
class AccountUnsafe implements Account {
private Integer balance;
public AccountUnsafe(Integer balance) {
this.balance = balance;
}
@Override
public Integer getBalance() {
synchronized (this) {
return this.balance;
}
}
@Override
public void withdraw(Integer amount) {
synchronized (this) {
this.balance -= amount;
}
}
}
interface Account { // 获取余额 Integer getBalance();
// 取款
void withdraw(Integer amount);
/**
* 方法内会启动 1000 个线程,每个线程做 -10 元 的操作
* 如果初始余额为 10000 那么正确的结果应当是 0
*/
static void demo(Account account) {
List<Thread> ts = new ArrayList<>();
for (int i = 0; i < 1000; i++) {
ts.add(new Thread(() -> {
account.withdraw(10);
}));
}
long start = System.nanoTime();
ts.forEach(Thread::start);
ts.forEach(t -> {
try {
t.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
});
long end = System.nanoTime();
System.out.println(account.getBalance()
+ " cost: " + (end-start)/1000_000 + " ms");
}
}
```java
0 cost: 92 ms
AtomicInteger无锁实例
class AccountCas implements Account {
private AtomicInteger balance;
public AccountCas(int balance) {
this.balance = new AtomicInteger(balance);
}
@Override
public Integer getBalance() {
return balance.get();
}
@Override
public void withdraw(Integer amount) {
/*while(true) {
// 获取余额的最新值
int prev = balance.get();
// 要修改的余额
int next = prev - amount;
// 真正修改
if(balance.compareAndSet(prev, next)) {
break;
}
}*/
// 乘以负一就是将正数改为负数,代表减掉amount
balance.getAndAdd(-1 * amount);
}
}
0 cost: 90 ms