AtomicIntegerFieldUpdater 对普通变量进行升级
    使用场景:偶尔需要一个原子get-set操作
    注意点::
    可见范围
    不支持修改static类型的变量

    1. public class AtomicIntegerFieldUpdaterDemo implements Runnable{
    2. static Candidate tom;
    3. static Candidate peter;
    4. // 对包装成原子类的变量不能添加static
    5. public static class Candidate{
    6. volatile int score;
    7. }
    8. public static AtomicIntegerFieldUpdater<Candidate> scoreUpdater = AtomicIntegerFieldUpdater.newUpdater(Candidate.class,"score");
    9. @Override
    10. public void run() {
    11. for (int i = 0; i < 1000; i++) {
    12. peter.score++;
    13. scoreUpdater.getAndIncrement(tom);
    14. }
    15. }
    16. public static void main(String[] args) throws InterruptedException {
    17. tom = new Candidate();
    18. peter = new Candidate();
    19. AtomicIntegerFieldUpdaterDemo r = new AtomicIntegerFieldUpdaterDemo();
    20. Thread t1 = new Thread(r);
    21. Thread t2 = new Thread(r);
    22. t1.start();
    23. t2.start();
    24. t1.join();
    25. t2.join();
    26. System.out.println(peter.score);
    27. System.out.println(tom.score);
    28. }
    29. }