一图流
代码示例
升级类原子类
public static class Person { // 1. 要求 升级类原子类可以访问到 // 2. 要求有 volatile 修饰 public volatile Integer integerScore; public volatile int basicScore; public Person(Integer integerScore, int basicScore) { this.integerScore = integerScore; this.basicScore = basicScore; } @Override public String toString() { return "Person{" + "score1=" + integerScore + ", score2=" + basicScore + '}'; } } public static void main(String[] args) throws InterruptedException { // 1.1 将类的引用属性原子化 // 1.2 <类class, 属性class> // TODO 待测试 AtomicReferenceFieldUpdater<Person, Integer> integerScoreUpdater = AtomicReferenceFieldUpdater.newUpdater( Person.class, // 要升级的引用属性所属类 class Integer.class, // 要升级的引用属性 class "integerScore" // 要升级的属性名 ); // 2.1 将类的Integer属性原子化 // 2.2 <类class> AtomicIntegerFieldUpdater<Person> BasicScoreUpdater = AtomicIntegerFieldUpdater.newUpdater( Person.class, // 要升级的 Integer 类型的属性所属类 class "basicScore" // 要升级的 Integer 类型的属性名 ); // 用于线程不安全操作 Person danger = new Person(0, 0); // 用于线程安全操作 Person safe = new Person(0, 0); Runnable updateScore = new Runnable() { @Override public void run() { // 基本类型 danger.basicScore++; BasicScoreUpdater.getAndIncrement(safe); } }; Thread[] threads = new Thread[10000]; for (int i = 0; i < 10000; i++) { threads[i] = new Thread(updateScore); } for (int i = 0; i < 10000; i++) { threads[i].start(); } for (int i = 0; i < 10000; i++) { threads[i].join(); } System.out.println("danger: " + danger); System.out.println("safe: " + safe); }
adder 累加器
private static AtomicLong atomicLong = new AtomicLong(0); private static LongAdder adderLong = new LongAdder(); private static Runnable atomicR = () -> { int times = 10000; for (int i = 0; i < times; i++) { atomicLong.getAndIncrement(); } }; private static Runnable adderR = () -> { int times = 10000; for (int i = 0; i < times; i++) { adderLong.increment(); } }; private static long testAtomic(int taskCount, Runnable runnable) { ExecutorService service = Executors.newFixedThreadPool(16); long start = System.currentTimeMillis(); for (int i = 0; i < taskCount; i++) { service.submit(runnable); } service.shutdown(); // 等待线程池任务执行完毕 while (!service.isTerminated()) { } long end = System.currentTimeMillis(); return end - start; } public static void main(String[] args) { int taskCount = 10000; long atomicResult = testAtomic(taskCount, atomicR); long adderResult = testAtomic(taskCount, adderR); // 1. use 1715 mills System.out.println("AtomicLong useTime: " + atomicResult + " count: " + atomicLong.get()); System.out.println("LongAdder useTime: " + adderResult + " count: " + adderLong.sum()); }