Java并发性问题-使用AtomicInteger计数器映射

Java并发性问题-使用AtomicInteger计数器映射,java,concurrency,synchronization,atomic,Java,Concurrency,Synchronization,Atomic,我有几个线程同时工作,以增加映射中的计数器。由于某些原因,以下不适用于计数器有时在以下索引中不递增是枚举类: public class TheoreticalWorkload{ private static final ConcurrentHashMap<Indices, AtomicInteger> WORKLOAD = new ConcurrentHashMap<Indices, AtomicInteger>(); public void upda

我有几个线程同时工作,以增加映射中的计数器。由于某些原因,以下不适用于计数器有时在以下索引中不递增是枚举类:

public class TheoreticalWorkload{

    private static final ConcurrentHashMap<Indices, AtomicInteger> WORKLOAD = new ConcurrentHashMap<Indices, AtomicInteger>();

    public void update(Indices id, Integer change){
        int i = WORKLOAD.get(id).addAndGet(change);
        System.out.println(i);
    }
}

我做错了什么?我认为将计数器声明为AtomicInteger会阻止多个线程同时访问它。谢谢。

此代码无法编译。请发布这样的内容。当它没有更新时,你确定这不是因为没有调用更新函数吗?@CarlosBribbiescas是的,我确定,因为它实际上两次打印同一个数字。让它两次打印同一个数字并不意味着更新函数被正确调用。您可以连续添加两个不同的存储桶,并将相同的数字打印两次。是否可以将打印更改为:System.out.printlnid++i?通过这种方式,您可以查看重复编号是否用于同一索引。