天天看點

atomic java_Java中關于atomic的了解及使用示例

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 }