Java多线程详解(五)--获取处理结果和异常

一、代码
线程池的处理结果、以及处理过程中的异常都被包装到Future中,并在调用Future.get()方法时获取,执行过程中的异常会被包装成ExecutionException,submit()方法本身不会传递结果和任务执行过程中的异常。
我们知道Runable和Callable的区别如下:
1.Runnable执行方法是run(),Callable是call()
2.实现Runnable接口的任务线程无返回值;实现Callable接口的任务线程能返回执行结果
3.call方法可以抛出异常,run方法若有异常只能在内部消化

所以,我们需要获取处理结果和捕获异常需要使用Callable。

/**
 * @program: xxx
 * @description:
 * @author: shuonar
 * @create: 2020-06-02 16:52
 **/
public class ExecutorsTest {
    public static void main(String[] args) {
        ExecutorService executorService = new ThreadPoolExecutor(
                10,
                10,
                10, TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(512),
                new ThreadPoolExecutor.DiscardPolicy());

        Callable<String> callable = new Callable<String>() {
            @Override
            public String call() throws Exception {
                throw new RuntimeException("i love exception");
            }
        };

        Future<String> future = executorService.submit(callable);
        try{
            String result = future.get();
        }catch (Exception e){
            e.printStackTrace();
        }

        executorService.shutdown();
    }
}

执行结果:

java.util.concurrent.ExecutionException: java.lang.RuntimeException: i love exception
    at java.util.concurrent.FutureTask.report(FutureTask.java:122)
    at java.util.concurrent.FutureTask.get(FutureTask.java:192)
    at com.keda.activiti.config.ExecutorsTest.main(ExecutorsTest.java:29)
Caused by: java.lang.RuntimeException: i love exception
    at com.keda.activiti.config.ExecutorsTest$1.call(ExecutorsTest.java:23)
    at com.keda.activiti.config.ExecutorsTest$1.call(ExecutorsTest.java:20)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)

二、获取单个结果

通过submit()向线程池提交任务后会返回一个Future,调用V Future.get()方法能够阻塞等待执行结果,V get(long timeout, TimeUnit unit)方法可以指定等待的超时时间。

三、获取多个结果

如果向线程池提交了多个任务,要获取这些任务的执行结果,可以依次调用Future.get()获得。

但对于这种场景,我们更应该使用ExecutorCompletionService,该类的take()方法总是阻塞等待某一个任务完成,然后返回该任务的Future对象。向CompletionService批量提交任务后,只需调用相同次数的CompletionService.take()方法,就能获取所有任务的执行结果,获取顺序是任意的,取决于任务的完成顺序:

public class ExecutorTest {
    public static void main(String[] args) {
        ExecutorService executorService = new ThreadPoolExecutor(
                10,
                10,
                100, TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(512),
                new ThreadPoolExecutor.AbortPolicy());
        List<Callable<String>> solves = new LinkedList<>();
        solves.add(new Callable<String>() {
            @Override
            public String call() throws Exception {
                return "i love callable 1";
            }
        });

        solves.add(new Callable<String>() {
            @Override
            public String call() throws Exception {
                Thread.sleep(6000);
                return "i love callable 2";
            }
        });

        solves.add(new Callable<String>() {
            @Override
            public String call() throws Exception {
                return "i love callable 3";
            }
        });

        try {
            solve(executorService, solves);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    private static void solve(Executor executor, Collection<Callable<String>> solves) throws Exception{
        CompletionService<String> ecs = new ExecutorCompletionService<String>(executor);
        for(Callable<String> solve : solves){
            ecs.submit(solve);
        }

        int size = solves.size();
        System.out.println(size);
        for (int i = 0; i < size + 1; i++) {
            String result = ecs.take().get();
            System.out.println(i + "---------" + result);
        }
    }
}

处理结果:

3
0---------i love callable 1
1---------i love callable 3
2---------i love callable 2

单个任务的超时时间

V Future.get(long timeout, TimeUnit unit)方法可以指定等待的超时时间,超时未完成会抛出TimeoutException

多个任务的超时时间

等待多个任务完成,并设置最大等待时间,可以通过CountDownLatch完成,下篇将详细了解CountDownLatch。待续~~~

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容