我正在使用 HiveMQ,每个线程都有两个客户端,并且我有一个启动这两个线程的主线程。我一直在System.nanoTime()
对发送(对于一个线程)和接收(对于另一个线程)进行计时,因此我可以将这些值相加以获得发送和接收给定数量的消息的总时间。我在 Java 中使用了 synchronized 块,wait()
以便notify()
计时器几乎在同一时间启动,因为一个线程必须唤醒另一个线程。我最后一次发送和接收的时间似乎在0-350 毫秒之间变化当我运行我的程序时,自然会发送和接收 15 条消息。对于上下文,服务器和客户端使用 localhost 作为服务器地址在同一台机器上运行。无论如何我可以在我的线程中获得更精确的时间(变化更小)?我想获得尽可能高的精度。
订阅者(发送客户端)的代码:
scheduler.waitToReceive(); // makes the SubThread wait until the PubThread is ready to send a message
System.out.println("Timer started");
startTime = System.nanoTime();
for (int i = 1; i <= 15; i++) {
Mqtt5Publish receivedMessage = receivingClient1.receive(MESSAGEWAITTIME,TimeUnit.SECONDS).get(); // receives the message using the "publishes" instance // .get() returns the object if available or throws a NoSuchElementException
PubSubUtility.convertMessage(receivedMessage); // Converts a Mqtt5Publish instance to string and prints
}
endTime = System.nanoTime();
Publisher(发布客户端)的代码:
readyToSend = true;
scheduler.notifyStartReceive(); // notifies SubThread it can starts receiving messages
startTime = System.nanoTime();
for (int i = 1; i <= 15; i++) {
publisher.publishWith()
.topic(publisherTopic) // publishes to the specified topic
.qos(MqttQos.EXACTLY_ONCE) // sets the quality of service to 2
.payload(convertedMessage) // the contents of the message
.send();
}
endTime = System.nanoTime();