同步跟异步一个最大的区别在于:同步单线就能实现,而异步则必须是多线程。
概念就不写了,直接上代码。(这里是异步)
下面这段代码线程休眠时间下面的时间必须大于上面的时间是为了把s赋值后直接return出去。
注意:被调用的Server的方法里面必须要有CallBack
public interface CallBack {
String callBack(String str);
}
public class Server {
public String serverTest(CallBack callBack,String msg){
System.out.println("=============");
return callBack.callBack(msg);
}
}
public class Client {
private Server server;
public Client(Server server) {
this.server = server;
}
private String s = "aaa";
public String clientTest(CallBack callBack,String msg) {
System.out.println("开始");
new Thread(() -> {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
s = server.serverTest(callBack, msg);
}).start();
System.out.println("结束");
try {
Thread.sleep(4000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return s;
}
public static void main(String[] args) {
Server server = new Server();
Client client = new Client(server);
System.out.println(client.clientTest(new CallBack() {
@Override
public String callBack(String str) {
try {
return "" + str.charAt(0);
} catch (Exception e) {
return "出现错误";
}
}
}, "zdfbgzcb"));
}
}