zoukankan      html  css  js  c++  java
  • Java8-Atomic

    
    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;
    import java.util.concurrent.atomic.AtomicInteger;
    import java.util.stream.IntStream;
    
    public class Atomic1 {
    
        private static final int NUM_INCREMENTS = 1000;
    
        private static AtomicInteger atomicInt = new AtomicInteger(0);
    
        public static void main(String[] args) {
            testIncrement();
            testAccumulate();
            testUpdate();
        }
    
        private static void testUpdate() {
            atomicInt.set(0);
    
            ExecutorService executor = Executors.newFixedThreadPool(2);
    
            IntStream.range(0, NUM_INCREMENTS)
                    .forEach(i -> {
                        Runnable task = () ->
                                atomicInt.updateAndGet(n -> n + 2);
                        executor.submit(task);
                    });
    
            ConcurrentUtils.stop(executor);
    
            System.out.format("Update: %d
    ", atomicInt.get());
        }
    
        private static void testAccumulate() {
            atomicInt.set(0);
    
            ExecutorService executor = Executors.newFixedThreadPool(2);
    
            IntStream.range(0, NUM_INCREMENTS)
                    .forEach(i -> {
                        Runnable task = () ->
                                atomicInt.accumulateAndGet(i, (n, m) -> n + m);
                        executor.submit(task);
                    });
    
            ConcurrentUtils.stop(executor);
    
            System.out.format("Accumulate: %d
    ", atomicInt.get());
        }
    
        private static void testIncrement() {
            atomicInt.set(0);
    
            ExecutorService executor = Executors.newFixedThreadPool(2);
    
            IntStream.range(0, NUM_INCREMENTS)
                    .forEach(i -> executor.submit(atomicInt::incrementAndGet));
    
            ConcurrentUtils.stop(executor);
    
            System.out.format("Increment: Expected=%d; Is=%d
    ", NUM_INCREMENTS, atomicInt.get());
        }
    
    }
    
  • 相关阅读:
    hasCode in Java
    如何区分同一Class的不同实例对象
    如何构建XML文件
    Spring <context:property-placeholder/>的作用
    关于List的几个方法
    Java 中那些不常用的关键字
    设计模式
    Java源代码阅读-Object.toString()
    修复启动项
    centos关闭防火前
  • 原文地址:https://www.cnblogs.com/bilaisheng/p/10210901.html
Copyright © 2011-2022 走看看