【问题标题】:How to keep looping an function in another class and pass return value to another class如何保持循环另一个类中的函数并将返回值传递给另一个类
【发布时间】: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


    【解决方案1】:

    所以这是一个相当广泛的解决方案空间 - 你可以想象有很多方法可以做你在这里描述的事情。

    我解决这个问题的方法是创建一个可以接受 ping 持续时间的功能接口。然后将其中的一个 lamba 传递到您的 ping 函数中。这样它就可以回调到您需要的任何类。

    您的代码将如下所示:

    import java.io.IOException;
    import java.net.InetAddress;
    import java.time.Duration;
    import java.time.Instant;
    
    @FunctionalInterface
    interface DurationAcceptor
    {
        void acceptPing(Long l);
    }
    
    class Server implements DurationAcceptor
    {
        private volatile Long serverStatus;
    
        @Override public void acceptPing(Long l)
        {
            serverStatus = l;
        }
    }
    
    public class Ping
    {
        public static void main(String... args)
        {
            Server server = new Server();
            Ping ping = new Ping();
            while(true)
            {
                Ping.ping("localhost", server::acceptPing);
            }
        }
    
        public static void ping(String host, DurationAcceptor acceptor)
        {
            Instant startTime = Instant.now();
            try {
                InetAddress address = InetAddress.getByName(host);
                if (address.isReachable(1000))
                {
                    acceptor.acceptPing(Duration.between(startTime, Instant.now()).toMillis());
                }
            } catch (IOException e) {
                // Host not available, nothing to do here
            }
            acceptor.acceptPing(Duration.ofDays(1).toMillis());
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2021-12-18
      • 2021-09-16
      • 1970-01-01
      • 2014-02-24
      • 1970-01-01
      • 2022-01-05
      • 2018-02-05
      • 1970-01-01
      相关资源
      最近更新 更多