一个java用future的实例...
详细的不说了..看看代码吧
public static void main(String[] args) throws InterruptedException, ExecutionException {
System.out.println("====勇者悄悄进入了宫殿");
//通过线程池管理多线程
ExecutorService threadPool = Executors.newCachedThreadPool();
//线程池提交一个异步任务
System.out.println("====勇者安放了一个炸弹,并设定10分钟后爆炸");
Future<HashMap<String,String>> future = threadPool.submit(new Callable<HashMap<String,String>>() {
public HashMap<String,String> call() throws Exception {
System.out.println("炸弹开始倒计时....");
Thread.sleep(10000);
System.out.println("炸弹启动...滴滴滴滴滴!!!!");
return new HashMap<String,String>(){
{this.put("futureKey", "Boom~炸弹爆炸了");}
};
}
});
System.out.println("====勇者放完炸弹后骑着自己的小马飞快的回到了家");
boolean flag = true;
while(flag){
Thread.sleep(1000);
if(future.isDone() && !future.isCancelled()){
HashMap<String,String> futureResult = future.get();
System.out.println("====远方传来了好消息,结果是:"+futureResult.get("futureKey"));
flag = false;
}else{
System.out.println("====勇者还在家静静的喝茶,等待着好消息的到来");
}
}
//关闭线程池
if(!threadPool.isShutdown()){
threadPool.shutdown();
}
}