【发布时间】:2022-01-11 09:37:11
【问题描述】:
假设我有一个函数可以将 ping 响应时间返回到我的服务器地址。
public class Ping{
public static Long ping(String host) {
Instant startTime = Instant.now();
try {
InetAddress address = InetAddress.getByName(host);
if (address.isReachable(1000)) {
return Duration.between(startTime, Instant.now()).toMillis();
}
} catch (IOException e) {
// Host not available, nothing to do here
}
return Duration.ofDays(1).toMillis();
}}
另一个类创建一个 server 对象来存储所有必需的值(例如“localhost”)。
serverStatus.setConnectivity(Ping.ping("localhost").doubleValue());
我能否在 Ping 类中继续循环 ping 函数并将返回结果传递给另一个类 StatusMapper 中的 serverStatus 设置器。或者在 StatusMapper 类中循环 ping 函数,如下所示
double ping = 0;
while true{
ping = Ping.ping("localhost").doubleValue();
}
serverStatus.setConnectivity(ping);
或者有没有更好的方法?
【问题讨论】:
标签: java loops infinite-loop