我想知道如何同步以下多线程,以便我仍然可以并行运行线程而不会导致多个对象被保存。
public void setupRender() {
ExecutorService executorService = Executors.newFixedThreadPool(10);
final Map<Integer, String> map = Collections.synchronizedMap(new HashMap<Integer, String>());
for (int i = 0; i < 10; i++) {
executorService.execute(new Runnable() {
@Override
public void run() {
parse(map);
}
});
System.out.println("map size " + map.size() + " loop " + i);
}
}
public void parse(Map<Integer, String> map) {
for (int j = 0; j < 100; j++) {
if (map.containsKey(j)) {
System.out.println("Update");
//session.update(map.getKey(j));
} else {
System.out.println("add to map " + j);
String obj = "test";
map.put(j, obj);
System.out.println("save");
//session.save(obj);
}
if (j % 50 == 0) {
System.out.println("commit");
//tx.commit();
}
}
}
结果,请注意如何将相同键的多个对象添加到映射中,但更糟糕的是保存到数据库中导致重复的数据库条目。
map size 0 loop 0
map size 0 loop 1
add to map 0
commit
add to map 1
add to map 0
commit
add to map 2
add to map 3
add to map 4
add to map 2
add to map 5
add to map 6
map size 1 loop 2
add to map 7
add to map 8
add to map 9
commit
map size 10 loop 3
commit
add to map 5