3 importjava.util.concurrent.atomic.AtomicInteger;4 importjava.util.function.DoubleUnaryOperator;5 importjava.util.function.IntUnaryOperator;6 import static java.lang.Float.*;7
8 public classAtomicPrac {9 public static voidmain(String[] args) {10 AtomicDemo atomicDemo = newAtomicDemo();11 atomicDemo.setNumberA(new AtomicInteger(3));12 for (int i = 1; i <= 10; i++) {13 newThread(atomicDemo).start();14 }15
16 AtomicInteger j=new AtomicInteger(4);17 System.out.println(j.incrementAndGet());18 System.out.println(updateAndGetInt(j,p -> p/2));19
20 //double型数据
21 AtomicFloat k = new AtomicFloat(5);22 System.out.println(updateAndGetDouble(k,p -> p/2));23
24 }25 //模拟底层实现:
26 public static floatupdateAndGetDouble(AtomicFloat i, DoubleUnaryOperator operator){27 while(true){28 float prev=i.get();//得到当前值
29 float next=(float) operator.applyAsDouble(prev);//将旧值传入,让接口的某个方法完成具体运算,返回计算结果30 //重写compareAndSet
31 if(i.compareAndSet(prev,next)){32 returnnext;33 }34 }35 }36 public static intupdateAndGetInt(AtomicInteger i, IntUnaryOperator operator){37 while(true){38 int prev=i.get();//得到当前值
39 int next=operator.applyAsInt(prev);//将旧值传入,让接口的某个方法完成具体运算,返回计算结果
40 if(i.compareAndSet(prev,next)){41 returnnext;42 }43 }44 }45 //模拟底层实现:
46 }47 class AtomicDemo implementsRunnable {48 publicAtomicInteger numberA;49
50 public voidrun() {51 try{52 Thread.sleep(200);53 } catch(InterruptedException e) {54 e.printStackTrace();55 }56 System.out.println(Thread.currentThread().getName() + ":" +getNumberA());57 }58
59 public intgetNumberA() {60 return numberA.updateAndGet(x -> x*2);61 }62
63 public voidsetNumberA(AtomicInteger numberA) {64 this.numberA =numberA;65 }66 }67
68 //对于使用双精度型的数据对应AtomicLong 自定义AtomicDouble 转换doubleToLongBits(1.00);69 //对于使用单精度型的数据对应AtomicInteger 自定义AtomicFloat 转换floatToIntBits(1.00);
70 class AtomicFloat extendsNumber {71
72 privateAtomicInteger bits;73
74 publicAtomicFloat() {75 this(0f);76 }77
78 public AtomicFloat(floatinitialValue) {79 bits = newAtomicInteger(floatToIntBits(initialValue));80 }81
82 public final boolean compareAndSet(float expect, floatupdate) {83 returnbits.compareAndSet(floatToIntBits(expect),84 floatToIntBits(update));85 }86
87 public final void set(floatnewValue) {88 bits.set(floatToIntBits(newValue));89 }90
91 public final floatget() {92 returnintBitsToFloat(bits.get());93 }94
95 public floatfloatValue() {96 returnget();97 }98
99 public final float getAndSet(floatnewValue) {100 returnintBitsToFloat(bits.getAndSet(floatToIntBits(newValue)));101 }102
103 public final boolean weakCompareAndSet(float expect, floatupdate) {104 returnbits.weakCompareAndSet(floatToIntBits(expect),105 floatToIntBits(update));106 }107
108 public double doubleValue() { return (double) floatValue(); }109 public int intValue() { return (int) get(); }110 public long longValue() { return (long) get(); }111 }