线程安全的计数器

使用ConcurrentHashMap和AtomicInteger实现,示例代码如下:

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

public class SynchronousCounter {

    public static void main(String[] args) {
        
        ConcurrentHashMap<String, AtomicInteger> countMap = new ConcurrentHashMap<String, AtomicInteger>();
        
        //有则放弃,无则设置
        AtomicInteger count = countMap.putIfAbsent("grid1", new AtomicInteger(0));
        System.out.print(count);
        
        //获取并加1
        int precount = countMap.get("grid1").getAndIncrement();
        System.out.print(precount);
        
        //获取当前值
        int nowcount = countMap.get("grid1").get();
        System.out.print(nowcount);
        
    }

}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 译序 本指南根据 Jakob Jenkov 最新博客翻译,请随时关注博客更新:http://tutorials.j...
    高广超阅读 5,198评论 1 68
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,026评论 19 139
  • 1. 原子性布尔 AtomicBoolean AtomicBoolean 类为我们提供了一个可以用原子方式进行读和...
    高广超阅读 5,720评论 1 14
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 173,678评论 25 708
  • 冬天吃的肉,夏天都知道。 这时节,瘦高个,细长腿,才是王道。我虽难以望其项背,但也不想自暴自弃。于是,几周来,缩减...
    文静文阅读 132评论 0 0