gpt4 book ai didi

java - 多线程环境下Executor Service清除map值

转载 作者:行者123 更新时间:2023-11-30 02:25:42 26 4
gpt4 key购买 nike

我这里有一个情况。我正在使用执行器服务来利用多线程。所以现在我试图向映射添加一个值,并在完成该循环后立即清除每个线程的值。我为此编写了以下代码。

我创建了一个 map ,并保存每次迭代的值并清除它。但当我使用 Executor Service 时,我相信它创建了 10 个线程并将值(value)添加到 map 中。这就是为什么我能够看到多个值,即使我只是添加一个值并清除它。

那么我如何清除循环中每个事务的 map :(

代码:

public class Test1 {
public static void main(String[] args){
ExecutorService executor = Executors.newFixedThreadPool(10);
final Multimap<Object, Object> map = Multimaps.synchronizedMultimap(ArrayListMultimap.create());

final List<String> listA = new ArrayList<String>();
listA.add("e");
listA.add("f");
listA.add("g");
final List<String> listB = new ArrayList<String>();
listB.add("e");
listB.add("f");
listB.add("g");
final List<String> listC = new ArrayList<String>();
listC.add("e");
listC.add("f");
listC.add("g");


for (final String stateId : listA) {
for (final String gradeList : listB) {
for (final String subjectList : listC) {
executor.execute(new Runnable() {
@Override
public void run() {
map.clear();
map.put("f", "hi");
System.out.println("map before "+map);

System.out.println("map after "+map);
}
});
}

}
}
executor.shutdown();
try {
executor.awaitTermination(24L, TimeUnit.HOURS);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

}

输出:

map before {f=[hi, hi]}
map before {f=[hi]}
map before {f=[hi]}
map before {f=[hi]}
map before {f=[hi]}
map before {f=[hi]}
map before {f=[hi]}
map before {f=[hi]}
map after {f=[hi]}
map after {f=[hi]}
map after {f=[hi]}
map before {f=[hi, hi]}
map before {f=[hi, hi]}
map after {f=[hi]}
map after {f=[hi]}
map before {f=[hi]}
map after {f=[hi]}
map before {f=[hi]}
map after {f=[hi]}
map before {f=[hi]}
map after {f=[hi]}
map after {f=[hi]}
map before {f=[hi]}
map before {f=[hi]}
map before {f=[hi]}
map after {f=[hi]}
map before {f=[hi]}
map after {f=[hi]}
map after {f=[hi]}
map before {f=[hi]}
map before {f=[hi]}
map after {f=[hi]}
map after {f=[hi, hi]}
map after {f=[hi]}
map before {f=[hi]}
map before {f=[hi]}
map before {f=[hi]}
map after {f=[hi]}
map after {f=[hi]}
map before {f=[hi]}
map before {f=[hi]}
map after {f=[hi]}
map after {f=[hi]}
map before {f=[hi]}
map after {f=[hi]}
map after {f=[hi]}
map after {f=[hi]}
map after {f=[hi]}
map before {f=[hi]}
map before {f=[hi]}
map after {f=[hi]}
map after {f=[hi]}
map after {f=[hi]}
map after {f=[hi]}

最佳答案

简单 - javadoc明确指出:

This class is not threadsafe when any concurrent operations update the multimap. Concurrent read operations will work correctly. To allow concurrent update operations, wrap your multimap with a call to Multimaps.synchronizedListMultimap(com.google.common.collect.ListMultimap).

换句话说:您不能只采用任何方便的集合类并向其抛出多个线程 - 而不采取进一步的预防措施。

关于java - 多线程环境下Executor Service清除map值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45716521/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com