使用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);
}
}