JUC-12.5-Future 和 FutureTask

Future 表示异步计算的结果。它提供了检查计算是否完成的方法,以等待计算的完成,并获取计算的结果。下面的例子中submit执行了一个Callable类型的任务列表然后得到了Futuer类型的结果列表result。

get()方法

等待计算完成,然后获取其结果。

isDone()方法

用来查询任务是否做完,

例子如下:

public class TestFuture {

    public static void main(String[] args) throws Exception {
        /*新建一个Callable任务*/
        Callable<Integer> callableTask = new Callable<Integer>() {
            @Override
            public Integer call() throws Exception {
                System.out.println("--->开始执行任务!");
                TimeUnit.SECONDS.sleep(2);//休眠2秒
                return 2;
            }
        }; 
        ExecutorService executor = Executors.newCachedThreadPool();
        Future<Integer> result = executor.submit(callableTask);
        executor.shutdown();
        while(!result.isDone()){//isDone()方法可以查询子线程是否做完
            System.out.println("子线程正在执行");
            TimeUnit.SECONDS.sleep(1);//休眠1秒
        }
        try {
            System.out.println("子线程执行结果:"+result.get());
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
    }
}

结果

猜你喜欢

转载自www.cnblogs.com/wf-zhang/p/12093047.html