import com.alibaba.fastjson.JSONObject; import java.io.IOException; import java.util.*; public class CallBackUtil { public EventHandlerOnMessageResult; 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(EventHandlerOnMessageResult, 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); } }
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)