同步调用和异步调用
同步调用:
调用者等待被调用者返回结果(执行完)才执行下一步
优点: 代码简单
缺点: 若被调用者执行的是耗时操作,会产生阻塞
异步调用:
调用者不用等待被调用者的返回结果也可以执行下一步
优点:若被调用者执行的是耗时操作,不会产生阻塞
缺点: 代码较复杂
还是不太懂?
举个例子:
同步调用:就像一个专情的屌丝男追求一个女孩,等待着这个女孩的回应,在等待回应之前这个男的不会去勾搭别的女孩。
异步调用:就好比一个渣男对女孩A发起追求(请求),等待女孩A回复的时候,这期间他又去勾搭女孩B。。。。
代码:
同步调用:
public class syncCall
{
public String Wait()
{
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("女:同意了");
return "同意了";
}
public void watchDog()
{
String string=Wait();
System.out.println("男:你"+string+",我知道了!");
}
public static void main(String[] args) {
syncCall sync=new syncCall();
sync.watchDog();
}
}
执行结果是延时3秒打印输出
异步调用:
public interface onEnd
{
void callBack(String message);
}
public class asyncCall
{
public String Wait()
{
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("女:同意了");
return "同意了";
}
//接口进行回调
public void watchDog(onEnd end)
{
new Thread(new Runnable()
{
@Override
public void run() {
String message=Wait();
end.callBack(message);
}
}).start();
}
public static void main(String[] args) {
asyncCall sync=new asyncCall();
sync.watchDog(new onEnd() {
@Override
public void callBack(String message) {
System.out.println("男:你"+message+",我知道了!");
}
});
while (true){
System.out.println("渣男在追求别的女孩!");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
执行结果:
还没有评论,来说两句吧...