概念介绍
同步调用
一种阻塞式调用,调用方要等待对方执行完毕才返回,它是一种单向调用。
我们之前所遇见的几乎都是同步调用,比如我们在A方法中调用B方法,必须等到B执行完,才能执行A中在B方法下面的代码,或者说,一定是被调用的B先执行完。
异步调用
一种类似消息或事件的机制,不过它的调用方向刚好相反,接口的服务在收到某种讯息或发生某种事件时,会主动通知客户方。
也就是说,异步调用不需要等待被调用方执行完毕之后再往下执行,它是不许要这个等待的。
回调
一种双向调用模式,也就是说,被调用方在接口被调用时也会调用对方的接口。
同步回调模拟
先设计一个回调的接口
public interface Callback {
void process(int status);
}
public class MyCallback implements Callback {
@Override
public void process(int status) {
System.out.println("处理成功,返回状态为:" + status);
}
}
模拟服务器端
public class Server {
public void response(Callback callback, String msg) throws InterruptedException {
System.out.println("服务器获得请求:" + msg);
//模拟消息处理,等待两秒钟
Thread.sleep(2000);
System.out.println("服务器端处理成功! ");
//处理完消息,调用回调方法,告知客户端
callback.process(200);//200代表处理成功
}
}
模拟客户端
public class Client {
Server server;
public Client(Server server) {
this.server = server;
}
// //同步回调
// public void request(final String msg) throws InterruptedException {
// System.out.println("客户端发送请求消息:" + msg);
// server.response(new MyCallback(),msg);
// System.out.println("客户端已经发消息给服务器端,请稍等。。。");
// }
//异步回调
public void request(final String msg){
System.out.println("客户端发送请求消息:" + msg);
new Thread(()->{
try {
server.response(new MyCallback(),msg);
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();
System.out.println("客户端已经发消息给服务器端,请稍等。。。");
}
}
测试
public class Test {
public static void main(String[] args) throws InterruptedException {
Server server = new Server();
Client client = new Client(server);
//由客户发送一个消息模拟一下
client.request("我要充值");
}
}