文章目录
简介
该类的实例操作能保证原子性,多个线程下可以保证线程安全
原子整数AtomicInteger相关API
public class Test15 {
public static void main(String[] args) {
AtomicInteger i = new AtomicInteger(2);
System.out.println(i.incrementAndGet()); // ++i 先2+1再打印得到最新的结果3
System.out.println(i.getAndIncrement()); // i++ 先得到最新的结果3打印再3+1
System.out.println(i.get()); // 4
System.out.println(i.getAndAdd(5)); // 先获取值最新的结果4打印 再4+5
System.out.println(i.get()); // 9
System.out.println(i.addAndGet(5)); // 先9+5=14再获取打印
}
}
public class Test16 {
public static void main(String[] args) {
AtomicInteger i = new AtomicInteger(2);
System.out.println(i.updateAndGet(value -> value * 10)); // 2*10更新后获取打印
// updateAndGet(i, value -> value * 2);
System.out.println(i.get());
}
/**
* @Description: updateAndGet的底层源码
* @Param i:
* @Param operator:
* @return void
* @date 2021/11/4 18:40
*/
public static void updateAndGet(AtomicInteger i, IntUnaryOperator operator) {
int prev, next;
do {
prev = i.get(); // 拿到当前值
next = operator.applyAsInt(prev); // 返回通过计算后的值
// CAS操作,如果当前值i没有被其他线程所改变(也就是i=AtomicInteger i = new AtomicInteger(2)声明中的i),那么把next值赋值给当前值i
} while (! i.compareAndSet(prev, next));
}
}
原子引用
AtomicReference
不论是float 还是double都是浮点数,而计算机是二进制的,浮点数会失去一定的精确度。只能无限接近于那个值,我们就要使用BigDecimal类型的表示余额,它是一个引用对象,不能用原子整数,这时候可以用原子引用包装该BigDecimal,保证线程安全
public interface Account {
// 获取余额
BigDecimal getBalance();
void withdraw(BigDecimal amount);
/**
* @Description: 启动一千个线程去并发,一个线程花掉10块钱,计算并发时间和结果,理想应该是为0
* @Param account:账户类
* @date 2021/11/4 13:00
*/
static void demo(Account account) {
List<Thread> threadList = new ArrayList<>();
long start = System.nanoTime();
for (int i = 0; i < 1; i++) {
threadList.add(new Thread(() -> {
account.withdraw(BigDecimal.TEN);
}));
}
threadList.forEach(Thread::start);
threadList.forEach(t -> {
try {
t.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
});
long end = System.nanoTime();
System.out.println(account.toString() + "余额为:" + account.getBalance() + "cost:" + (end - start)/1000_00 + "ms");
}
}
class AccountCAS implements Account {
private AtomicReference<BigDecimal> balance;
public AccountCAS(BigDecimal balance) {
this.balance = new AtomicReference<>(balance);
}
@Override
public BigDecimal getBalance() {
return balance.get();
}
/**
* @Description: 使用CAS机制,尝试保证线程安全,
* @Param amount:
* @return void
* @date 2021/11/4 13:16
*/
@Override
public void withdraw(BigDecimal amount) {
while (true) {
BigDecimal prev = balance.get();
BigDecimal next = prev.subtract(amount);
if (balance.compareAndSet(prev, next)){
break;
}
}
}
}
虽然BigDecimal类方法是线程安全的,但涉及多个方法的操作并不是原子性,就如withdraw方法中,用到了get()和subtract(amount)方法组合,所以不能保证线程安全,要用原子引用去包装。但是会有ABA问题,下面代码展示了ABA问题
@Slf4j
public class Bank {
static AtomicReference<String> ref = new AtomicReference<>("A");
public static void main(String[] args) throws InterruptedException {
log.info("main start...");
// 获取值 A
// 这个共享变量被它线程修改过?
String prev = ref.get();
other();
sleep(1);
// 尝试改为 C,中途有其他线程修改了,又有其他线程改回了原来值,它是不能感知的,CAS返回true
log.info("change A->C {}", ref.compareAndSet(prev, "C"));
}
private static void other() throws InterruptedException {
new Thread(() -> {
log.info("change A->B {}", ref.compareAndSet(ref.get(), "B"));
}, "t1").start();
sleep(1);
new Thread(() -> {
log.info("change B->A {}", ref.compareAndSet(ref.get(), "A"));
}, "t2").start();
}
}
可以用AtomicStampedReference,解决ABA问题
AtomicStampedReference
@Slf4j
public class Bank {
static AtomicStampedReference<String> ref = new AtomicStampedReference<>("A", 0); // 初试版本号为0
public static void main(String[] args) throws InterruptedException {
log.info("main start...");
// 获取值 A
// 这个共享变量被它线程修改过?
String prev = ref.getReference();
int stamp = ref.getStamp(); // 获取版本号
log.info("{}", stamp);
other();
sleep(1);
// 尝试改为 C
log.info("change A->C {}", ref.compareAndSet(prev, "C", stamp, stamp + 1)); // 更新成功了版本号就+1
}
private static void other() throws InterruptedException {
new Thread(() -> {
int stamp = ref.getStamp();
log.info("change A->B {}", ref.compareAndSet(ref.getReference(), "B", stamp, stamp + 1)); // 更新成功了版本号就+1
}, "t1").start();
sleep(1);
new Thread(() -> {
int stamp = ref.getStamp();
log.info("change B->A {}", ref.compareAndSet(ref.getReference(), "A", stamp, stamp + 1)); // 更新成功了版本号就+1
}, "t2").start();
}
}
这样可以避免ABA问题
AtomicMarkableReference
我们不关心值改变了多少次,只关心是否改过,就可以用AtomicMarkableReference,它的版本号是一个布尔值。
@Slf4j
public class Bank {
static AtomicMarkableReference<String> ref = new AtomicMarkableReference<>("A", true); // 初试版本号为0
public static void main(String[] args) throws InterruptedException {
log.info("main start...");
// 获取值 A
// 这个共享变量被它线程修改过?
String prev = ref.getReference();
other();
sleep(1);
// 尝试改为 C
log.info("change A->C {}", ref.compareAndSet(prev, "C", true, false)); // 期待为true更新成功了版本号就false
}
private static void other() throws InterruptedException {
new Thread(() -> {
log.info("change B->A {}", ref.compareAndSet(ref.getReference(), "A", true, false)); // 期待为true更新成功了版本号就false
}, "t2").start();
}
}
只要有人改了一次,就不能执行成功
原子数组
我们修改数组元素,希望保证线程安全,关注的是数组元素,而不是数组本身
package demo;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.atomic.AtomicIntegerArray;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
/**
* @author pangjian
* @ClassName Test
* @Description 启动线程去改变数组内元素的值,执行一万1,理想应该更改均摊到各元素的值都为10000
* @date 2022/6/14 21:22
*/
public class Test {
public static void main(String[] args) {
demo(
() -> new int[10],
(array) -> array.length,
(array, index) -> array[index]++,
array -> System.out.println(Arrays.toString(array))
);
demo(
() -> new AtomicIntegerArray(10),
(array) -> array.length(),
(array, index) -> array.getAndIncrement(index),
array -> System.out.println(array)
);
}
// 参数1,提供数组、可以是线程不安全数组或线程安全数组参数
// 2,获取数组长度的方法
// 参数3,自增方法,回传array,index
// 参数4,打印数组的方法
// supplier提供者无中生有()->结果
// function函数 一个参数一个结果 (参数)->结果 , BiFunction (参数1, 参数2)->结果
// consumer消费者 一个参数没结果 (参数)->void BiConsumer.(参数1,参数2)->
private static <T> void demo(
Supplier<T> arraySupplier,
Function<T, Integer> lengthFun,
BiConsumer<T, Integer> putConsumer,
Consumer<T> printConsumer) {
List<Thread> ts = new ArrayList<>();
T array = arraySupplier.get();
int length = lengthFun.apply(array);
for (int i = 0; i < length; i++) {
// 每个线程对数组作10000次操作
ts.add(new Thread(() -> {
for (int j= 0; j< 10000; j++) {
putConsumer.accept(array, j%length);
}
}));
}
ts.forEach(t -> t.start());
ts.forEach(t -> {
try {
t.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
});
printConsumer.accept(array);
}
}
字段更新器
利用字段更新器,可以针对对象的某个域(Field)进行原子操作,只能配合volatile修饰的字段使用,否则会出现异常
package demo;
import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
/**
* @author pangjian
* @ClassName Test1
* @Description 希望多线程下修改Student类实例属性name时,能保证线程安全
* @date 2022/6/14 21:50
*/
public class Test1 {
public static void main(String[] args) {
Student student = new Student();
AtomicReferenceFieldUpdater updater = AtomicReferenceFieldUpdater.newUpdater(Student.class, String.class, "name");
// 第三个参数要原始值,因为一开始实例的属性值为null
boolean a = updater.compareAndSet(student, null, "张三");
System.out.println(a);
System.out.println(student);
}
}
class Student {
volatile String name;
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
'}';
}
}
原子累加器
对于原子整数类的累加方法,用原子累加器性能更高
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.LongAdder;
import java.util.function.Consumer;
import java.util.function.Supplier;
/**
* @author pangjian
* @ClassName Test2
* @Description TODO
* @date 2022/6/14 21:57
*/
public class Test2 {
public static void main(String[] args) {
demo(
() -> new AtomicLong(0),
(adder) -> adder.getAndIncrement()
);
demo(
() -> new LongAdder(),
adder -> adder.increment()
);
}
private static <T> void demo(Supplier<T> supplier, Consumer<T> consumer) {
T adder = supplier.get();
List<Thread> list = new ArrayList<>();
for (int i = 0; i < 4; i++) {
list.add(new Thread(() -> {
for (int j = 0; j < 500000; j++) {
consumer.accept(adder);
}
}));
}
long start = System.nanoTime();
list.forEach(t -> t.start());
list.forEach(t -> {
try {
t.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
});
long end = System.nanoTime();
System.out.println(adder + "cost:" + (end - start)/1000_000);
}
}