我有2个功能。第一个 discoverHosts() 向其他计算机发送请求消息。在此之后,它使用 await 命令进入睡眠状态。一个单独的威胁在收到响应时调用 handleMessage() 函数。在他处理完响应后,他使用 notifyAll() 让 discoderHosts() 知道他必须检查是否收到了所有响应。
DiscoverHosts() 在调用该函数时会等待。但是,当单独的威胁调用handleMessage() 时,发现主机() 不会在handleMessage 调用signalAll() 时唤醒。我在调试时检查了是否调用了 signalAll(),就是这种情况。在我的项目的其他地方,我有几乎相同的代码。
你们中有人知道我在忽略什么吗?
private final Lock lock = new ReentrantLock();
private final Condition allReceived = lock.newCondition();
private void discoverHosts() throws Exception {
lock.lock();
externalNodes = new HashMap<String, NodeAddress>();
Message msg = new Message(null, "REQUEST_IP");
logger.debug("Broadcasting ip request, waiting responses");
channel.send(msg);
// TODO:Write a time-out
while (channel.getView().size() - 1 != externalNodes.keySet().size()) {
logger.debug("Channel: " + (channel.getView().size() - 1));
logger.debug("Responses: "+ externalNodes.keySet().size());
allReceived.await();
}
logger.debug("All answers received");
lock.unlock();
}
protected void handleMessage(Message msg) {
lock.lock();
if (!((String) msg.getObject()).matches("IP_RESPONSE:[0-9.]*"))
return;
logger.debug("Received answer from " + msg.getObject());
String ip = ((String) msg.getObject()).replaceAll("IP_RESPONSE:", "");
// externalHostIps.add(ip);
NodeAddress currentAddress = new NodeAddress(ip, msg.getSrc());
externalNodes.put(ip, currentAddress);
logger.debug("Signalling all threads");
allReceived.signalAll();
lock.unlock();
logger.debug("Unlocked");
}
记录器输出:
4372 [main] DEBUG com.conbit.webhackarena.monitor.monitor.Monitor@3b91eb - Broadcasting ip request, waiting responses
4372 [main] DEBUG com.conbit.webhackarena.monitor.monitor.Monitor@3b91eb - Channel: 1
4372 [main] DEBUG com.conbit.webhackarena.monitor.monitor.Monitor@3b91eb - Responses: 0
4394 [Incoming-1,webhackarena,leendert-K53SV-53745] DEBUG com.conbit.webhackarena.monitor.monitor.Monitor@3b91eb - Received answer from IP_RESPONSE:192.168.1.106
4396 [Incoming-1,webhackarena,leendert-K53SV-53745] DEBUG com.conbit.webhackarena.monitor.monitor.Monitor@3b91eb - Signalling all threads
4397 [Incoming-1,webhackarena,leendert-K53SV-53745] DEBUG com.conbit.webhackarena.monitor.monitor.Monitor@3b91eb - Unlocked