栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

java FutureTask使用

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

java FutureTask使用

public static Integer getTotal1(){
        try {
            System.out.println("开始getTotal1");
            Thread.sleep(6000);
            System.out.println("结束getTotal1");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 1;
    }

    public static Integer getTotal2(){
        try {
            System.out.println("开始getTotal2");
            Thread.sleep(3000);
            System.out.println("结束getTotal2");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 3;
    }

使用普通方式调用上面两个方法得到返回数据需要耗时9秒多, 一个方法6秒多,一个方法3秒多,

        long start = System.currentTimeMillis();
        System.err.print(getTotal1());
        System.err.print(getTotal2());
        long end = System.currentTimeMillis();
        System.err.print("耗时=====>"+(end-start));

使用FutureTask 则只需要6秒多就可以得到两个方法的返回数据

       long start = System.currentTimeMillis();
        Callable ca1 = new Callable(){
            @Override
            public Integer call() throws Exception {
                return getTotal1();
            }
        };
        FutureTask recharge1 = new FutureTask(ca1);
        new Thread(recharge1).start();


        Callable ca2 = new Callable(){
            @Override
            public Integer call() throws Exception {
                return getTotal2();
            }
        };
        FutureTask recharge2 = new FutureTask(ca2);
        new Thread(recharge2).start();

        System.err.print(recharge1.get());
        System.err.print("n====================n");
        System.err.print(recharge2.get());
        long end = System.currentTimeMillis();
        System.err.print("耗时=====>"+(end-start));

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/632509.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号