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());
        }
    
    }
    
  • 相关阅读:
    自定义博客园skin
    c++11: <thread>学习
    《明日方舟》Python版公开招募工具
    Python列表
    Python基础
    C#常用修饰符
    C#单例类的实现
    云服务器反黑客入侵攻防实录(一)
    在CentOS7.6上安装自动化运维工具Ansible以及playbook案例实操
    技术漫谈 | 远程访问和控制云端K8S服务器的方法
  • 原文地址:https://www.cnblogs.com/bilaisheng/p/10210901.html
Copyright © 2011-2022 走看看