1.Callable构建线程的使用

示例代码:

class MyThread implements Callable<Integer> {

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

public class CallableDemo {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        FutureTask<Integer> futureTask = new FutureTask<>(new MyThread());
        new Thread(futureTask, "A").start();
        int a = 1;
        //会阻塞
        int b = futureTask.get();
        System.out.println("count=" + (a + b));
    }
}

运行结果:

count=56

Callable构建有返回值的线程,且线程内部抛出异常。
可用于构建分布式任务,最后汇总任务结果。

posted on 2021-03-18 11:09  whn051799  阅读(58)  评论(0编辑  收藏  举报