Future模式在jdk5中有实现
其特点是:不阻塞等待函数的执行结果,而是立即返回一个Future对象,Future对象就像一个提货单,等函数执行完成再去提货
核心类是 Host 和 FutureData
public class Main {
/**
* @param args
*/
public static void main(String[] args) throws Exception{
Host host = new Host();
Data f1 = host.request(5, 'c');
Data f2 = host.request(5, 'd');
Data f3 = host.request(5, 'e');
Thread.sleep(2000);
System.out.println(f1.getData());
}
}
package com.justel.fs.future;
public class FutureData implements Data{
private boolean ready = false; //readData是否已经完成
private RealData realData;
@Override
public synchronized String getData() {
while(!ready){
try {
wait();
} catch (InterruptedException e) {
}
}
return realData.getData();
}
public RealData getRealData() {
return realData;
}
public synchronized void setRealData(RealData realData) {
if(ready) return;
this.realData = realData;
ready = true;
notifyAll();
}
}
package com.justel.fs.future;
public class RealData implements Data{
private int n;
private char c;
public RealData(int n, char c){
this.n = n;
this.c = c;
}
@Override
public String getData() {
String string = "";
try {
for (int i = 0; i < n; i++) {
string += c;
Thread.sleep(1000);
}
} catch (InterruptedException e) {
}
return string;
}
}
package com.justel.fs.future;
public class Host {
public Data request(final int n, final char c){
final FutureData futureData = new FutureData();
new Thread(){
public void run(){
RealData realData = new RealData(n, c);
futureData.setRealData(realData);
}
}.start();
return futureData;
}
}
分享到:
评论