java学习

java学习

 

java future 线程模式

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());
}
}

posted on 2019-02-18 10:08 杨军威 阅读(25) 评论(0)  编辑  收藏


只有注册用户登录后才能发表评论。


网站导航:
 

导航

统计

常用链接

留言簿

随笔档案

搜索

最新评论

阅读排行榜

评论排行榜