public class AtomicIntegerFieldUpdaterDemo2 implements Runnable{
AtomicIntegerFieldUpdater<Candidate> aifu = AtomicIntegerFieldUpdater.newUpdater(Candidate.class, "score");
private static Candidate tom;
public static class Candidate {
volatile int score;
}
@Override
public void run() {
for (int i = 0; i < 100; i++) {
aifu.getAndIncrement(tom);
}
}
}
基于反射的实用工具,可以对指定类的指定 volatile int 字段进行原子更新
所以,被AtomicIntegerFieldUpdater描述的字段,应当是 volatile 修饰的,并且是int类型的.
然后我们使用两个线程并行去递增该数值,并查看结果
public static void main(String[] args) throws InterruptedException {
tom = new Candidate();
AtomicIntegerFieldUpdaterDemo2 r1 = new AtomicIntegerFieldUpdaterDemo2();
Thread t1 = new Thread(r1);
Thread t2 = new Thread(r1);
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println(tom.score);
}
可以得到正确的结果,表示线程安全!