欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

AtomicIntegerFieldUpdater sample code

程序员文章站 2022-07-14 12:46:44
...

import java.util.concurrent.atomic.*;

class Container {
  public volatile int no;
}

class Task extends Thread {
  private AtomicIntegerFieldUpdater<Container> updater =
    AtomicIntegerFieldUpdater.newUpdater(Container.class, "no");
  private Container c;

  public Task(Container c) {
    this.c = c;
  }
  @Override
  public void run() {
    System.out.println(updater.getAndIncrement(c));  
    System.out.println(updater.getAndIncrement(c));  
  }
}

public class UpdaterUsage {
  public static void main (String [] args) {
    Container c = new Container();
    Task t1 = new Task(c);
    Task t2 = new Task(c);
    t1.start();
    t2.start();
  }  
}