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

来源:互联网 发布:苹果手机微信数据恢复 编辑:程序博客网 时间:2024/05/16 23:42

通过 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();    }}
0 0
原创粉丝点击