并发编程-Future模式

Future模式有点类似于商品订单.比如在网购时,当看重一件商品时,就可以提交订单,当订单处理完成后,在家里等待商品送货上门即可.或者说更形象的: 我们发送Ajax请求的时候,页面是异步的进行后台处理,用户无须一直等待请求的结果,可以继续浏览或操作其他内容.
并发编程-Future模式_第1张图片
实际代码如下:

Data:

## Data:
public interface Data {
    public String getRequest();
}

RealData:

## RealData:
public class RealData implements Data{
    private String result;

    public RealData(String queryStr){
        System.out.println("根据" + queryStr + "进行查询,这是一个很耗时的操作...");
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("操作完毕,获取结果");
        result = "查询结果";
    }

    @Override
    public String getRequest() {
        return result;
    }
}

FutureData:


## FutureData:

import java.util.concurrent.CountDownLatch;

public class FutureData implements Data {
    private RealData realData;

    private boolean isReady = false;

    private CountDownLatch countDownLatch = new CountDownLatch(1);

    public void setRealData(RealData realData){
        if (isReady){
            return;
        }
        this.realData = realData;
        isReady = true;
        countDownLatch.countDown();
//        notify();
    }

    @Override
    public String getRequest() {
        if (!isReady){
            try {
                countDownLatch.await();
//                wait();
                System.out.println("正在等待");
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        return this.realData.getRequest();
    }
}

FutureClient:

## FutureClient:
public class FutureClient {
    public Data request(final String queryStr){
        final FutureData futureData = new FutureData();
        new Thread(() -> {
            RealData realData = new RealData(queryStr);
            futureData.setRealData(realData);
        }).start();
        return  futureData;
    }
}

Main:

## Main:
public class Main {
    public static void main(String[] args) {
        FutureClient futureClient = new FutureClient();
        Data data = futureClient.request("请求参数");
        System.out.println("请求发送成功");
        System.out.println("做其他的事情");
        String select = data.getRequest();
        System.out.println(select);
    }
}

你可能感兴趣的:(并发编程)