import com.alibaba.fastjson.JSONObject;
import java.io.IOException;
import java.util.*;
public class CallBackUtil {
public EventHandler<JSONObject> 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<JSONObject> 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);
}
}