Callable 接口创建线程 可以有返回值

2018-03-12  本文已影响31人  zheting

Callable 接口实现的线程可以有返回值和抛出异常

package com.sheting.concurrent.callable;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

/**
 * Create Time: 2018-03-09 10:41
 *
 * @author sheting
 */
public class TestCallable {

    public static void main(String[] args) {

        ThreadDemo threadDemo = new ThreadDemo();

        //执行Callable,需要FutureTask实现类的支持,用于接受运算的结果。FutureTask是Future接口的实现类。
        FutureTask<Integer> result = new FutureTask<>(threadDemo);

        //启动线程
        new Thread(result).start();

        try {
            //获取线程运算后的结果
            Integer sum = result.get();
            System.out.println(sum);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }
}

class ThreadDemo implements Callable<Integer> {

    @Override
    public Integer call() throws Exception {
        int sum = 0;
        for (int i = 1; i <= 100; i++) {
            sum += i;
        }
        return sum;
    }
}
上一篇 下一篇

猜你喜欢

热点阅读