多线程设计模式 -- futrue

数据接口
public interface Data {
    public abstract String getContent();
}


真正需要的数据对象
public class RealData implements Data {
    private final String content;
    public RealData(int count, char c) {
        System.out.println("        making RealData(" + count + ", " + c + ") BEGIN");
        char[] buffer = new char[count];
        for (int i = 0; i < count; i++) {
            buffer[i] = c;
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
            }
        }
        System.out.println("        making RealData(" + count + ", " + c + ") END");
        this.content = new String(buffer);
    }
    public String getContent() {
        return content;
    }
}



//异步数据
public class FutureData implements Data {
	private RealData realdata = null;
	private boolean ready = false;

	public synchronized void setRealData(RealData realdata) {
		//如果已经准备好直接返回不用再设置
		if (ready) {
			return; // balk
		}
		this.realdata = realdata;
		//设置值已准备好
		this.ready = true;
		//唤醒等待线程
		notifyAll();
	}

	public synchronized String getContent() {
		//如没有准备好,线程等待
		while (!ready) {
			try {

				wait();
			} catch (InterruptedException e) {
			}
		}
		return realdata.getContent();
	}
}



获取数据代理类
public class Host {
    public Data request(final int count, final char c) {
        System.out.println("    request(" + count + ", " + c + ") BEGIN");

        // (1) 建立FutureData的实体
        final FutureData future = new FutureData();

        // (2) 为了建立RealData的实体,启动新的线程
        new Thread() {                                      
            public void run() {                             
                RealData realdata = new RealData(count, c);
                future.setRealData(realdata);
            }                                               
        }.start();                                          

        System.out.println("    request(" + count + ", " + c + ") END");

        // (3) 取回FutureData实体,作为传回值
        return future;
    }
}


//测试类
public class Main {
    public static void main(String[] args) {
        System.out.println("main BEGIN");
        Host host = new Host();
        //请求数据
        Data data1 = host.request(10, 'A');
        Data data2 = host.request(20, 'B');
        Data data3 = host.request(30, 'C');

        System.out.println("main otherJob BEGIN");
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
        }
        System.out.println("main otherJob END");

        //不需要直接等待返回,可以同时去执行别的任务
        System.out.println("data1 = " + data1.getContent());
        System.out.println("data2 = " + data2.getContent());
        System.out.println("data3 = " + data3.getContent());
        System.out.println("main END");
    }
}


1.异步方法调用返回值
2.分离 "准备返回值"与"使用返回值"
3.变形--不让人等待的Future参与者
4.变形--会改变的Future参与者

你可能感兴趣的:(设计模式,多线程,C++,c,C#)