线程 —— 通过 Callable 对象创建线程

通过 Callable 对象创建线程。
通过 Callable 创建线程与 Runnable 不同的是:Callable 的 call 方法可以有返回值,而且这个方法可以声明抛出异常。

/**
 * Created by liwei on 16/7/19.
 * Callable : 是指带泛型的接口
 * 这里指定的泛型其实是 call() 方法的返回值类型
 */
public class MyCallable implements Callable {
    @Override
    public Object call() throws Exception {
        for(int x=0;x<100;x++){
            System.out.println(Thread.currentThread().getName() + ":" + x);
        }
        return null;
    }
}

调用(通过上一节介绍的线程池的方式调用):

public class CallableDemo {

    public static void main(String[] args) {
        // 创建线程池对象
        ExecutorService pool = Executors.newFixedThreadPool(2);
        // 可以执行 Runnable 对象或者 Callable 对象代表的线程
        pool.submit(new MyCallable());
        pool.submit(new MyCallable());
        // 结束
        pool.shutdown();
    }
}

下面是一个线程求和的例子

线程类,注意,这个线程实现了泛型接口, call 方法声明了返回值。

/**
 * Created by liwei on 16/7/19.
 * 线程求和的案例
 */
public class MyCallable implements Callable<Integer> {

    private Integer number;

    public MyCallable(Integer number){
        this.number =number;
    }

    @Override
    public Integer call() throws Exception {
        Integer sum = 0;
        for (int x=1;x<=number;x++){
            sum += x;
        }
        return sum;
    }
}

执行线程:

public class CallableDemo {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        // 创建线程池对象
        ExecutorService pool = Executors.newFixedThreadPool(2);
        // 可以执行 Runnable 或者 Callable 对象代表的线程
        Future<Integer> future1 = pool.submit(new MyCallable(100));
        Future<Integer> future2 = pool.submit(new MyCallable(200));
        // TODO: 16/7/19
        Integer i1 = future1.get();
        Integer i2 = future2.get();
        System.out.println(i1);
        System.out.println(i2);
        // 结束
        pool.shutdown();
    }
}
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值