注意事项
1.更新的对象属性必须使用 public volatile 修饰,数据更新后保证线程间可见
2.对象的属性修改类型原子类都是抽象类,每次使用必须使用静态方法newUpdater()创建一个更新器
示例演示
public class AccountBank {
private Long id;
private String bankName;
public volatile long money;
//使用静态方法newUpdater()创建一个更新器,设置想要更新的类的属性
AtomicLongFieldUpdater<AccountBank> atomicLongFieldUpdater = AtomicLongFieldUpdater.newUpdater(AccountBank.class,"money");
//提供一个线程安全的递增金额的方法
public Long updateMoney(AccountBank accountBank){
return atomicLongFieldUpdater.getAndIncrement(accountBank);
}
//省略getter setter方法...
}
public static void main(String[] args) throws InterruptedException {
int size = 100;
AccountBank accountBank = new AccountBank();
CountDownLatch countDownLatch = new CountDownLatch(size);
for (int i = 1; i <= size; i++) {
new Thread(() -> {
try {
for (int i1 = 0; i1 < 1000; i1++) {
Long aLong = accountBank.updateMoney(accountBank);
System.out.println("aLong = " + aLong);
}
} catch (Exception e){
e.fillInStackTrace();
} finally {
countDownLatch.countDown();
}
},"T_"+i).start();
}
countDownLatch.await();
System.out.println("accountBank.getMoney() = " + accountBank.getMoney());
}
演示结果
.......
aLong = 99990
aLong = 99991
aLong = 99992
aLong = 99993
aLong = 99994
aLong = 99995
aLong = 99996
aLong = 99997
aLong = 99998
aLong = 99999
accountBank.getMoney() = 100000