java代码仿真ajax异步等待(future)

源于蚂蚁课堂的学习,点击这里查看(老余很给力)

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机制,原理相同

猜你喜欢

转载自blog.csdn.net/yxh13521338301/article/details/106214732