Java中使用Future获取线程异步执行结果的使用

package demo.feture;

import java.util.concurrent.*;

/**
 * created by yuyufeng on 2017/8/17.
 */
public class Test {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        long begin = System.currentTimeMillis();
        ExecutorService executorService = Executors.newFixedThreadPool(10);

        Future future = executorService.submit(new Callable() {
            public Object call() throws Exception {
                System.out.println("Asynchronous Callable1");
                //异步开始执行任务(需要2秒)
                Thread.sleep(2000);
                return "Callable Result1";
            }
        });
        Future future2 = executorService.submit(new Callable() {
            public Object call() throws Exception {
                //异步开始执行任务(需要2秒)
                System.out.println("Asynchronous Callable2");
                Thread.sleep(3000);
                return "Callable Result2";
            }
        });
        //主线程执行任务2.5秒(操作1)
        Thread.sleep(1000);
        //此时任务1 已经完成,获取结果(如果未完成,则future.get()会阻塞等待结果)
        System.out.println("future.get() = " + future.get());

        //主线程执行任务3 秒(操作2)
        Thread.sleep(3000);

        System.out.println("future.get() = " + future.get());
        System.out.println("future.get() = " + future2.get());
        executorService.shutdown();
        System.out.println(System.currentTimeMillis() - begin);
        //操作1 主线程执行任务2.5秒, 累计耗时 5506毫秒,约等于主线程总耗时。
        //操作1 主线程执行任务1秒, 累计耗时 5006毫秒,主线程在操作1之后,又等了1秒去获取第一次异步执行的结果,所以就是主线程的操作时间+1秒与约等于5秒。
        //future.get()的作用就是去获取异步执行的结果,如果异步执行完毕则不会阻塞
    }

}

Feture获取异步执行结果方法在请求超时放弃时的使用:

 

package demo.feture;

import java.util.concurrent.*;

/**
 * created by yuyufeng on 2017/8/17.
 */
public class TestTimeOut {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        long begin = System.currentTimeMillis();
        ExecutorService executorService = Executors.newFixedThreadPool(10);

        Future future = executorService.submit(new Callable() {
            public Object call() throws Exception {
                System.out.println("Asynchronous Callable1");
                //异步开始执行任务(需要2秒)
                Thread.sleep(5000);
                System.out.println("执行完毕~");
                return "Callable Result1";
            }
        });
        try {
            //获取异步执行结果,如果过3秒,则直接结束!
            Object result = future.get(3000, TimeUnit.MILLISECONDS);
            System.out.println("future.get() = " + result);
        } catch (TimeoutException e) {
            System.out.println("你太慢了,不想要结果,直接结束吧~" + e.getLocalizedMessage());
        }
        executorService.shutdown();
        System.out.println(System.currentTimeMillis() - begin);
    }
}

/**
 *执行结果
 * Asynchronous Callable1
 *你太慢了,不想要结果,直接结束吧~null
 *3005
 *执行完毕~
 */

 

 

 

 

 

你可能感兴趣的:(Java,[并发])