zoukankan      html  css  js  c++  java
  • 高并发-原子性-AtomicInteger

    线程不安全:

    //请求总次数
    private static int totalCount = 10000;
    //最大并发数
    private static int totalCurrency = 100;
    //计数初始值
    private static int count = 0;

    public static void main(String[] args) throws InterruptedException {
    final CountDownLatch countDownLatch = new CountDownLatch(totalCount);
    final Semaphore semaphore = new Semaphore(totalCurrency);
    ExecutorService executorService = Executors.newCachedThreadPool();
    for (int i = 0; i < totalCount; i++) {
    executorService.execute(new Runnable() {
    @Override
    public void run() {
    try {
    semaphore.acquire();
    //本身线程不安全
    count++;
    semaphore.release();
    countDownLatch.countDown();
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    }
    });
    }
    //其他线程运行完成执行下面操作
    countDownLatch.await();
    executorService.shutdown();
    System.out.println(count);
    }

    线程安全:

     //总共请求次数10000次 数值给大点 不然效果不明显
    private static int totalCount = 10000;
    //最大并发数 100个 数值给大点 不然效果不明显
    private static int totalCurrency = 100;
    // private static int count = 0;
    //使用原子类修饰
    private static AtomicInteger atomicInteger = new AtomicInteger(0);

    public static void main(String[] args) throws InterruptedException {

    final CountDownLatch countDownLatch = new CountDownLatch(totalCount);
    final Semaphore semaphore = new Semaphore(totalCurrency);
    ExecutorService executorService = Executors.newCachedThreadPool();
    for (int i = 0; i < totalCount; i++) {
    executorService.execute(() -> {
    try {
    semaphore.acquire();
    atomicInteger.incrementAndGet();
    semaphore.release();
    countDownLatch.countDown();
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    });
    }
    //其他线程完成各自任务 countDownLatch.count==0
    countDownLatch.await();
    executorService.shutdown();
    System.out.println(atomicInteger);

    }


  • 相关阅读:
    CodeforcesBeta Round #19 D. Points 离线线段树 单点更新 离散化
    挑战练习题3.3 POJ 2886 Who Gets the Most Candies? 树状数组
    hdu4288 Coder 离线线段树 单点更新 区间求和 离散化?
    zoj 1610 Count the Colors 线段树 区间更新
    51nod 1307 绳子与重物 二分+dfs / 并查集
    51nod 1116 K进制下的大数 暴力/数论
    Wannafly2016-12-27 SPOJ-INTSUB 数学
    C++——Vector
    LEDE Project
    Raspberry Pi 3 with Openwrt
  • 原文地址:https://www.cnblogs.com/coderdxj/p/9946636.html
Copyright © 2011-2022 走看看