【发布时间】:2020-08-27 14:34:36
【问题描述】:
我有一个被多个线程同时调用的方法。在其中,我试图处理下面 sn-p 解释的场景:
Map<Object,Long> syncMap = Collections.synchronizedMap(normalHashMap);
Runnable mapOperations = () -> {
synchronized (syncMap) {
if (MapUtils.isNotEmpty(syncMap))
{
Object currentCount = syncMap.get(entryKey);
// Every thread should execute this once. Every thread brings a value and that gets added up and stored for this "key"
syncMap.put(key, value + valueFromThisThread);
}
}
};
mapOperations.run();
每个线程都应该执行一次上面的块。每个线程都会带来一个 long 值,并且会为映射中的这个“键”条目添加并存储该值。
有人可以确认这是否可行吗?
【问题讨论】:
-
只是补充一点:为什么你认为,任何线程都会多次执行它?
-
只需将其设为
final使用synchronizedMap()时也不需要synchronized语句 -
@GiorgiTsiklauri 抱歉,我并不是说任何线程都会多次执行它,但“每个线程”都应该执行一次。
标签: java multithreading hashmap concurrenthashmap