public interface Data {
String getResult();
}
public class FutureData implements Data{
protected Data data=null;
protected boolean f=false;
public synchronized void setData(Data data) {
if(f) {
return;
}
f=true;
this.data=data;
notifyAll();
}
@Override
public synchronized String getResult() {
while (!f) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return data.getResult();
}
}
public class RealData implements Data{
protected String s;
public RealData(String name) {
StringBuffer sb=new StringBuffer("");
for (int i = 0; i < 10; i++) {
sb.append(name);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
s=sb.toString();
}
@Override
public String getResult() {
// TODO Auto-generated method stub
return s;
}
}
public class Client {
public Data request(final String ss) {
final FutureData f=new FutureData();
new Thread() {
public void run() {
RealData r=new RealData(ss);//模拟复杂的数据封装和处理
f.setData(r);
};
}.start();
return f;
}
public static void main(String[] args) {
Client client=new Client();
Data d = client.request("123");
System.out.println(d.getResult());
}
}
public class FutureTest {
public static void main(String[] args) throws InterruptedException, ExecutionException {
ExecutorService e=Executors.newFixedThreadPool(11);
FutureTask<String> f=new FutureTask<>(new Callable<String>() {
@Override
public String call() throws Exception {
Thread.sleep(5000);
return "aa";
}
});
e.submit(f);
System.out.println(f.get());
}
}