- AtomicInteger
- AtomicBoolean
- AtomicLong
AtomicInteger
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| package com.redisc;
import lombok.extern.slf4j.Slf4j;
import java.util.concurrent.atomic.AtomicInteger;
@Slf4j(topic = "c.Test") public class Run {
public static void main(String[] args) throws IllegalAccessException, InstantiationException, ClassNotFoundException { AtomicInteger i = new AtomicInteger(0);
System.out.println(i.incrementAndGet()); System.out.println(i.getAndIncrement());
i.getAndAdd(5); i.addAndGet(5);
i.updateAndGet(x -> x * 10); } }
|
其中 i.getAndAdd(-1 * amount);
相当于 java | 无锁实现临界区访问
1 2 3 4 5 6 7 8
| while (true) { int prev = balance.get(); int next = prev - amount; if (balance.compareAndSet(prev, next)) { break; } }
|
compareAndSet
方法是一个原始方法,上面的那些方法都可以用 compareAndSet
重写。