实现线程的第三种方式 实现Callable接口

package com.juc;


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

/**
 * Created by fuguowen on 2018/8/5 21:12
 */

/**
 * 一. 创建执行线程的方式三:实现Callable接口,相较于实现Runnable接口的方式,方法可以有返回值,并且可以抛出异常。
 *
 * 二。执行Callable方式,需要FutureTask实现类的支持,用于接受运算的结果,FutureTask是Future接口的实现类。
 */
public class TestCallable {
    public static void main(String[] args) {
        MyCallable mc = new MyCallable();
        //1.执行Callable方式,需要FutureTask实现类的支持,用于接受运算结果
        FutureTask<Integer> ft = new FutureTask<>(mc);
        new Thread(ft).start();
        //2.接受线程运算的结果
        try {
            Integer sum = ft.get();
            System.out.println(sum);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }
}
class MyCallable implements Callable<Integer>{
    @Override
    public Integer call() throws Exception {
        int sum=0;
        for (int i = 0; i <1000 ; i++) {
            sum+=i;
        }
        return sum;
    }
}

猜你喜欢

转载自blog.csdn.net/u011243684/article/details/81435805