Java回调函数

Java回调函数,第1张

Java回调函数
import com.alibaba.fastjson.JSONObject;

import java.io.IOException;
import java.util.*;

public class CallBackUtil {

    public EventHandler OnMessageResult;

    public CallBackUtil() {

    }

    public void CallFun(String param, Long timeout) {
        new Thread(() -> {
            try {
                waitResult(param, timeout);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }).start();
    }

    private void waitResult(String param, Long timeout) throws InterruptedException, IOException {
        JSonObject val = null;
        Date dtStart = new Date();
        while (true) {
            if ("成功".equals(param)) {
                val = new JSonObject();
                val.put("code", 200);
                val.put("message", "数据请求成功");
                break;
            }
            Thread.sleep(1000);
            //判断是否超时
            if (timeout > 0 && isTimeOut(dtStart, new Date(), timeout)) {
                val = new JSonObject();
                val.put("code", 408);
                val.put("message", "数据请求超时");
                break;
            }
        }
        if (onMessageResult != null) {
            OnMessageResult.EventHandler(null, val);
        }
    }

    private Boolean isTimeOut(Date dtStart, Date dtEnd, Long timeOut) {
        Long interval = (dtEnd.getTime() - dtStart.getTime());
        return interval >= timeOut;
    }
public class CallBackTest {

    public static void main(String[] args) {
        CallBackUtil util = new CallBackUtil();
        callFunIsLock(util.OnMessageResult, util);
    }

    public static void callFunIsLock(EventHandler OnMessageResult, CallBackUtil funClient) {
        funClient.onMessageResult = (Object sender, JSonObject obj) -> {
            if (onMessageResult == null) {
                System.out.println("回调后要做的事情~~~");
            } else {
                OnMessageResult.EventHandler(sender, obj);
            }
            System.out.println("回调的结果:" + obj.toJSonString());
        };
        funClient.CallFun("成功", 2000L);
    }

}

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/4692499.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-11-07
下一篇 2022-11-07

发表评论

登录后才能评论

评论列表(0条)

保存