我有一个 ConcurrentMap,它在我的可运行文件之外被实例化,但在可运行文件内/跨可运行文件共享和更新。我的 runnables 需要是并发的,但我的 concurrentMap 更新需要同步以防止替换以前的条目。有人可以告诉我我做错了什么。
public class ExecutionSubmitExample {
public static void main(String[] args) {
//Ten concurrent threads
ExecutorService es = Executors.newFixedThreadPool(10);
List<Future<Example>> tasks = new ArrayList<>();
ConcurrentHashMap<Integer, String> concurrentMap = new ConcurrentHashMap<>();
for (int x = 0; x < 10; x++) {
Example example = new Example(concurrentMap, x);
Future<Example> future = es.submit(example, example);
tasks.add(future);
}
try {
for (Future<Example> future : tasks) {
Example e = future.get();
}
for (Entry<Integer,String> obj : concurrentMap.entrySet()) {
System.out.println("key " + obj.getKey() + " " + obj.getValue());
}
es.shutdown();
} catch (ExecutionException e) {
throw new RuntimeException(e);
} catch (InterruptedException ie) {
throw new RuntimeException(ie);
}
}
}
可运行
public class Example implements Runnable {
ConcurrentHashMap<Integer, String> concurrentMap;
private int thread;
public Example(ConcurrentHashMap<Integer, String> concurrentMap, int thread) {
this.concurrentMap = concurrentMap;
this.thread = thread;
}
@Override
public void run() {
for (int i = 0; i < 3; i++) {
runAnalysis(i);
}
}
public synchronized void runAnalysis(int index) {
if(concurrentMap.containsKey(index)) {
System.out.println("contains integer " + index);
} else {
System.out.println("put " + index + " thread " + thread);
concurrentMap.put(index, "thread " + thread);
}
}
}
结果- 通知索引 0 被添加多次而不是一次。它应该由线程 0 添加并读取为线程 9 包含的内容。我不知何故需要将此方法与其他线程锁定,直到更新完成。
put 0 thread 0
put 0 thread 9
put 0 thread 6
put 0 thread 7
put 1 thread 7
put 0 thread 2
put 0 thread 1
put 0 thread 5
put 0 thread 3
put 0 thread 4
contains integer 1
contains integer 1
contains integer 1
contains integer 1
put 2 thread 7
put 1 thread 6
put 1 thread 9
put 1 thread 0
put 0 thread 8
contains integer 2
contains integer 2
contains integer 2
put 2 thread 2
put 2 thread 1
put 2 thread 5
put 2 thread 3
contains integer 1
contains integer 1
contains integer 2
contains integer 2
key 0 thread 8
key 2 thread 3
key 1 thread 0