1. 同步回调
- Callback
public interface Callback {
void onSuccess(String result);
void onFail(String result);
}
- Server
public class Server {
private static Map<String, String> map = new HashMap<>();
static {
map.put("1", "111");
map.put("2", "222");
}
public void query(String id, Callback callback) throws InterruptedException {
TimeUnit.SECONDS.sleep(10);
if (map.containsKey(id)) {
callback.onSuccess(map.get(id));
} else {
callback.onFail("no result for query");
}
}
}
- Client
public class Client {
public static void main(String[] args) throws InterruptedException {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-hh HH:mm:ss");
Server server = new Server();
Callback callback = new Callback() {
@Override
public void onSuccess(String result) {
System.out.println(format.format(new Date()) + " Success: " + result);
}
@Override
public void onFail(String result) {
System.out.println(format.format(new Date()) + " Fail: " + result);
}
};
System.out.println(format.format(new Date()) + " begin query...");
server.query("1", callback);
System.out.println(format.format(new Date()) + " finished");
}
}
- 运行结果
2020-10-11 11:32:51 begin query...
2020-10-11 11:33:01 Success: 111
2020-10-11 11:33:01 finished
2. 异步回调
-
Callback
同上 -
Server
同上 -
Client
public class Client {
public static void main(String[] args) {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-hh HH:mm:ss");
Server server = new Server();
Callback callback = new Callback() {
@Override
public void onSuccess(String result) {
System.out.println(format.format(new Date()) + " Success: " + result);
}
@Override
public void onFail(String result) {
System.out.println(format.format(new Date()) + " Fail: " + result);
}
};
System.out.println(format.format(new Date()) + " begin query...");
new Thread(() -> {
try {
server.query("1", callback);
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();
System.out.println(format.format(new Date()) + " do something else...");
}
}
- 运行结果
2020-10-11 11:36:08 begin query...
2020-10-11 11:36:08 do something else...
2020-10-11 11:36:18 Success: 111











网友评论