多线程使用callable返回值

runnable是执行工作的独立任务,但是它不返回任何值。如果要返回值,就需要用到callable,类型参数是泛型,参考下面的案例,返回值是在call()方法内

public class callable_test{
    public static void main(String[] args){
        //这里需要看下面的解释
        ExecutorService ex = Executors.newCachedThreadPool();

        ArrayList<Future<String>> list = new ArrayList<Future<String>>();
        for (int i = 0; i < 10; i++) {
            list.add(ex.submit(new callable_demo(i)));
        }
        for (Future<String> fs:list) {
            try {
                System.out.println(fs.get());
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }finally {
                ex.shutdown();
            }
        }
    }
}
class callable_demo implements Callable<String>{
    private int id;

    public callable_demo(int id) {
        this.id = id;
    }
    @Override
    public String call() throws Exception {
        String s = "hello word"+id;
        TimeUnit.MILLISECONDS.sleep(100);
        return s;
    }
}

Executor 显示地创建Thread对象,简化并发编程
newCachedThreadPool 将为每一个任务都创建一个线程
FixedThreadPool 一次性预先执行代价高昂的线程分配,可以节省时间,限制线程数量
SingleThreadExecutor 只有1个线程,好处是不需要在共享资源上同步

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值