线程池的学习(五)

本章主要 是手写一个Future模式

什么是Future模式呢:在主线程中调用线程任务,却可以在不影响主线程代码执行的情况下拿到任务执行结果【该模式像是Ajax(异步加载)】

---------------------------------------代码走起---------------------------------------

定义一个抽象类Data

public abstract class Data {
    public abstract String getRequestResult();
}

继承抽象类Data,实现任务返回值处理FutureData,其中的两个方法必须用synchronized 修饰,否则会报异常

Exception in thread "Thread-0" java.lang.IllegalMonitorStateException

public class FutureData extends Data {

    private boolean flag = false;
    private RealData realData;

    //读取data数据  本方法用于修改flag的值
    //第一次进来 flag必定是false 进行赋值
    public synchronized void setReadData(RealData realData) {
        if (flag){
            return ;
        }
        this.realData = realData;
        flag = true;
        notify();
    }

    @Override
    public synchronized String getRequestResult() {
        if(!flag){//flag = false时 阻塞,等setReadData()方法执行后 重新由notify();唤醒
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        return realData.getRequestResult();
    }
}

继承抽象类Data,实现任务处理 RealData

public class RealData extends Data {
    private String resultData;

    public RealData(String data){
        System.out.println("任务开始");
        try {
            Thread.sleep(10000);//模拟线程执行任务
        }catch (Exception e){
            e.printStackTrace();
        }
        System.out.println("任务结束");
        this.resultData = "1";
    }

    @Override
    public String getRequestResult() {
        return resultData;
    }
}

Future的客户端 FutureClient

public class FutureClient {

    public Data request(String requestData){
        FutureData futureData = new FutureData();
        new Thread(new Runnable() {
            @Override
            public void run() {
                RealData realData = new RealData(requestData);
                futureData.setReadData(realData);
            }
        }).start();
        return futureData;
    }
}

测试方法

@Test
public void test() {
    FutureClient client = new FutureClient();
    Data request = client.request("123");
    System.out.println(request.getRequestResult());
}

 

posted @ 2020-03-29 01:52  An-Optimistic-Person  阅读(61)  评论(0编辑  收藏  举报