我有一个程序,许多线程将他们的请求发布到PriorityQueue
。
之后,他们等待ConcurrentSkipListMap
的回复。有一个帖子可以发布ConcurrentSkipListMap
的答案。
以下代码行说明了这一点:
在程序初始化
PriorityQueue<Request> requests = new PriorityQueue<Request>();
ConcurrentSkipListMap<Long, Reponse> responsesReceived = new ConcurrentSkipListMap<Long, Reponse>();
在来电线程中
// Send request ...
Request r = ... // Elaborate the request
requests.add(r);
// ... then wait for an answer
Long id = r.getId();
while (responsesReceived.containsKey(id) == false) {
synchronized (responsesReceived) {
responsesReceived.wait();
}
}
Answer a = responsesReceived.take(id);
// Do other things ...
在响应处理程序线程中
// Wait for a remote answer
Answer answer = ...;
// Once received publish it in ConcurrentSkipListMap
responsesReceived.put(answer.getRequestId(), answer);
synchronized (responsesReceived) {
responsesReceived.notify();
}
// Go back and wait for a new answer...
问题
ConcurrentSkipListMap
?HashMap
锁(HashMap<Long,Object>
)吗? 我是java.util.concurrent API的新手,我有些疑惑......
答案 0 :(得分:1)
使用synchronized / wait / notify,您可以将任何对象用作锁定。至于将作业提交到队列并等待其结果,请查看ExcutorService
,Future
和CompletionService
。
答案 1 :(得分:0)
虽然这可行,但它可能不是表达您正在做的事情的最明确方式。我会为这些通知添加一个单独的“锁定”对象。
注意:除非你只有一个等待线程,否则我会使用notifyAll()。