带有返回值的 Callable 使用

4 篇文章 0 订阅
工作中很多涉及到多线程的地方都implemnets Runable 接口 或者是 extends Thread 抽象类,但是这样子的话得不到返回值。
如果以下场景:
     在多线程中计算值,线程结束后需要携带返回值。
这时就需要Callable接口,实现改接口后需要实现方法 call 。改接口需要ExecutorService的submit方法执行,执行结果包装在 Future<?>泛型类中。
通过Future类的get()方法取得返回值,get()是阻塞的,在线程执行前调用get()方法会一直阻塞着。
可以通过isDone()判断线程是否执行完成。


package com.afengzi.training.comcurrency;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

/**
* Created with IntelliJ IDEA.
* User: afengzi
* Date: 14-10-9
* Time: 下午5:06
* 实现有返回值的Callable接口
*/
public class Acallable{

    public static void main(String args[]){

        ExecutorService service = Executors.newCachedThreadPool() ;
        List<Future<String>> futures = new ArrayList<Future<String>>() ;
        for (int i = 0 ; i< 5 ; i++){
            Future<String> future = service.submit(new $Call(100)) ;
            futures.add(future) ;
        }
        service.shutdown();
        System.out.println("main -- "+Thread.currentThread().getName());
        for (Future<String> future : futures){
            if (future.isDone()){
                try {
                    System.out.println(future.get());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (ExecutionException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static class $Call implements Callable<String>{
        private int index ;

        public $Call(int index){
            this.index = index ;
        }
        @Override
        public String call() throws Exception {
            int first = 1 ;
            int second = 1 ;
            int third = 0 ;
            while (true){
                third = first+second ;
                if (third > index){
                    break;
                }
                first = second ;
                second = third ;
            }
            System.out.println("sub -- "+Thread.currentThread().getName());
            return third+"" ;
        }
    }


}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值