有的時候我們不需要直接申明一個原子變量,比如申明一個AtomicInteger對象,因爲原子變量本身就影響性能,還有就是隻是偶爾進行原子操作,比如在某一時刻段,那麼這個時候AtomicIntegerFieldUpdater或者AtomicLongFieldUpdater就顯得比較有用了,以AtomicIntegerFieldUpdater爲例子,基於反射的實用程序,可以對指定類的指定的volatile int字段進行原子更新
重要方法
@CallerSensitive
public static <U> AtomicIntegerFieldUpdater<U> newUpdater(Class<U> tclass,
String fieldName) {
return new AtomicIntegerFieldUpdaterImpl<U>
(tclass, fieldName, Reflection.getCallerClass());
}
通過傳入目標類和目標類的變量,對變量進行原子升級,通過反射返回AtomicIntegerFieldUpdater對象,通過這個對象就可以對這個變量進行原子操作
注意這個變量不能是靜態和私有的
案例:
/**
* 描述: 演示AtomicIntegerFieldUpdater的用法
*/
public class AtomicIntegerFieldUpdaterDemo implements Runnable{
static Candidate tom;
static Candidate peter;
public static AtomicIntegerFieldUpdater<Candidate> scoreUpdater = AtomicIntegerFieldUpdater
.newUpdater(Candidate.class, "score");
@Override
public void run() {
for (int i = 0; i < 10000; i++) {
peter.score++;
scoreUpdater.getAndIncrement(tom);
}
}
public static class Candidate {
//不能被static修飾,也不能爲私有
volatile int score;
}
public static void main(String[] args) throws InterruptedException {
tom=new Candidate();
peter=new Candidate();
AtomicIntegerFieldUpdaterDemo r = new AtomicIntegerFieldUpdaterDemo();
Thread t1 = new Thread(r);
Thread t2 = new Thread(r);
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println("普通變量:"+peter.score);
System.out.println("升級後的結果"+ tom.score);
}
}
執行結果:
普通變量:19128
升級後的結果20000