public class AtomicIntegerFieldUpdaterDemo implements Runnable{
static Candidate tom;
static Candidate peter;
public static final AtomicIntegerFieldUpdater<Candidate> scoreUpdater = AtomicIntegerFieldUpdater.newUpdater(Candidate.class,"score");
@Override
public void run() {
for (int i = 0; i < 100000; i++) {
peter.score ++;
scoreUpdater.getAndIncrement(tom);
}
}
public static class Candidate{
volatile int score =0 ;
}
public static void main(String[] args) throws InterruptedException {
tom = new Candidate();
peter = new Candidate();
AtomicIntegerFieldUpdaterDemo r = new AtomicIntegerFieldUpdaterDemo();
Thread thread = new Thread(r);
thread.start();
Thread thread1 = new Thread(r);
thread1.start();
thread.join();
thread1.join();
System.out.println("tom:"+tom.score);
System.out.println("peter:"+peter.score);
}
}