Java Future实例 以异步的方式让勇者给魔王宫殿放个炸弹

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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值