多线程和并发库应用九-callable

本节主要讲下 Callable和Future 的使用它俩很有意思的,一个产生结果,一个拿到结果。 Callable接口类似于Runnable,从名字就可以看出来了,但是Runnable不会返回结果,并且无法抛出返回结果的异常,而Callable功能更强大一些,被线程执行后,可以返回值,这个返回值可以被Future拿到,也就是说,Future可以拿到异步执行任务的返回值,下面来看一个简单的例子:

public class CallableAndFuture {
    public static void main(String[] args) throws ExecutionException, InterruptedException, TimeoutException {
        ExecutorService threadPool= Executors.newSingleThreadExecutor();
        Future future= threadPool.submit(new Callable<String>(){

            public String call() throws Exception {
              Thread.sleep(2000);
                return "hello";
            }
        });
        System.out.println("等待结果");

        System.out.println("结果"+future.get());
    }
}

FutureTask实现了两个接口,Runnable和Future,所以它既可以作为Runnable被线程执行,又可以作为Future得到Callable的返回值,那么这个组合的使用有什么好处呢?假设有一个很耗时的返回值需要计算,并且这个返回值不是立刻需要的话,那么就可以使用这个组合,用另一个线程去计算返回值,而当前线程在使用这个返回值之前可以做其它的操作,等到需要这个返回值时,再通过Future得到

public class FutureTaskTest {
    public static void main(String[] args) throws ExecutionException, InterruptedException, TimeoutException {
        Callable<Integer> callable = new Callable<Integer>() {
            public Integer call() throws Exception {
                int task=new Random().nextInt(5000);
                Thread.sleep(task);
                return task;
            }
        };
        FutureTask<Integer> future = new FutureTask<Integer>(callable);
        new Thread(future).start();
        try {
            System.out.println(future.get());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }
}

可以使用CompletionService去提交一组任务

public class CallableAndCompletion {
    public static void main(String[] args) throws ExecutionException, InterruptedException, TimeoutException {
        ExecutorService threadPool= Executors.newFixedThreadPool(10);
        CompletionService<Integer> com=new ExecutorCompletionService<Integer>(threadPool);
        for (int i=1;i<=10;i++){
            final int task=i;
            com.submit(new Callable<Integer>() {
                public Integer call() throws Exception {
                    Thread.sleep(new Random().nextInt(5000));
                    return task;
                }
            });
        }
        System.out.println("等待结果");

        for (int i=1;i<=10;i++){
            System.out.println("结果"+com.take().get());
        }


    }
}

文章来源:http://www.haha174.top/article/details/253560
项目源码:https://github.com/haha174/thread-learning.git

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值