package live.yanxiaohui.test;
/**
* @Description 真實數據
* @CSDN https://blog.csdn.net/yxh13521338301
* @Author: yanxh<br>
* @Date 2020-05-19 14:35<br>
* @Version 1.0<br>
*/
public class Real {
// 請求的結果
private String msg;
public Real(String message) {
System.out.println("請求發送的信息爲:" + message);
try {
// 假設這是邏輯處理,可能需要三秒
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// 設置請求結果
this.msg = "我是異步請求的結果";
}
// 獲取請求結果
public String getMsg(){
return msg;
}
}
package live.yanxiaohui.test;
/**
* @Description 虛擬數據,即等線程執行完數據才完整
* @CSDN https://blog.csdn.net/yxh13521338301
* @Author: yanxh<br>
* @Date 2020-05-19 14:34<br>
* @Version 1.0<br>
*/
public class Future {
// 對應的真實數據
private Real real;
/**
* 設置真實數據
* @param real
*/
public synchronized void setReal(Real real){
this.real = real;
notify();
}
public synchronized String getReal(){
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
return real.getMsg();
}
}
package live.yanxiaohui.test;
/**
* @Description todo
* @CSDN https://blog.csdn.net/yxh13521338301
* @Author: yanxh<br>
* @Date 2020-05-19 14:45<br>
* @Version 1.0<br>
*/
public class Test {
public static void main(String[] args) {
Future future = new Future();
new Thread(() -> {
future.setReal(new Real("我是異步請求的參數"));
}).start();
System.out.println("主線程執行");
String real = future.getReal();
System.out.println("線程獲取數據:" + real);
}
}
通過對象的wait和notify配合,使得主線程在獲取數據時進行等待,但是在獲取數據前,主線程和子線程互不干擾。
也就是主線程可以去做自己的事情。由此仿真callbale的future機制,原理相同