Future和FutureTask的区别

Future和FutureTask,他们在表面上都是向ExecutorService提交callback后返回的结果。

同时通过get()方法取得计算结果。

Future:

        ExecutorService executor = Executors.newFixedThreadPool(2);

        Future future = executor.submit(new Callable() {
            @Override
            public String call() throws Exception {
                Thread.sleep(1000 * 5);
                return "Hello ";
            }
        });

        System.out.printf("Finished.Result:%sr\r\n", future.get());

FutureTask:

        ExecutorService executor = Executors.newFixedThreadPool(2);

        // demo1
        FutureTask ft = new FutureTask<>(new Callable() {
            @Override
            public String call() throws Exception {
                System.out.println("loading data from database...");
                Thread.sleep(1000 * 5);
                return "ok";
            }
        });
        executor.submit(ft);

        System.out.printf("Finished.Result:%sr\r\n", ft.get());

FutureTask的乾坤在于,保证Callback只运行一次,内部通过状态来控制。请看FutureTask的run实现:

测试代码:

  ExecutorService executor = Executors.newFixedThreadPool(2);

        // demo1
        FutureTask ft = new FutureTask<>(new Callable() {
            @Override
            public String call() throws Exception {
                System.out.println("loading data from database...");
                Thread.sleep(1000 * 5);
                return "ok";
            }
        });
        executor.submit(ft);

        System.out.printf("Finished.Result:%sr\r\n", ft.get());

        System.out.println("Run again.");
        // 之前已经运行好了,这个run就直接返回
        executor.submit(ft);
        String result0 = ft.get();
        System.out.println("Finished result:" + result0);
此条目发表在IT分类目录,贴了, , 标签。将固定链接加入收藏夹。

发表评论

电子邮件地址不会被公开。

*