AtomicIntegerFieldUpdater 对普通变量进行升级
使用场景:偶尔需要一个原子get-set操作
注意点::
可见范围
不支持修改static类型的变量
public class AtomicIntegerFieldUpdaterDemo implements Runnable{
static Candidate tom;
static Candidate peter;
// 对包装成原子类的变量不能添加static
public static class Candidate{
volatile int score;
}
public static AtomicIntegerFieldUpdater<Candidate> scoreUpdater = AtomicIntegerFieldUpdater.newUpdater(Candidate.class,"score");
@Override
public void run() {
for (int i = 0; i < 1000; i++) {
peter.score++;
scoreUpdater.getAndIncrement(tom);
}
}
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);
}
}