我在同步我的idMap
. 此地图正用于两种run()
同时运行的方法。在第一个 run() 方法中,我只是将事件 id 值)映射到响应 id(键)。在第二个 run() 方法中,我希望获得具有相同响应 id(键)的事件 id(值)。但是,有时会有一些事件 ID,有时无法获得它们。该程序编译得很好,但我不是线程专家,我相信线程导致它idMap
不同步。我的问题很简单,我怎样才能使idMap
工作顺利进行并按照我的意图获取事件 ID?
ConcurrentHashMap<String, String> idMap = new ConcurrentHashMap<String, String>();
ConcurrentHashMap<String, ExecutorService> executors = new ConcurrentHashMap<String, ExecutorService>();
private final class ResponderTask implements Runnable {
private ResponderTask(Event event) {
this.event = event;
}
// 1st run()
public void run() {
idMap.put(response.getId(), event.getId());
}
}//end ResponderTask
private final class QuoteTask implements Runnable {
//constructor
//2nd run()
public void run() {
IdMap.get(response.getId());
}
}//end QuoteTask
public void onResponse(final Response response) {
ExecutorService quoteExecutor = executors.get(response.getId());
if (quoteExecutor == null) {
quoteExecutor = Executors.newSingleThreadExecutor();
executors.put(event.getId(), quoteExecutor);
}
quoteExecutor.execute(new ResponderTask(event));
}