va.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class Demo3 {
    //异步计算0-100的和
    //跟0-200的和
    public static void main(String[] args) throws InterruptedException, ExecutionException {
        //获取线程池
        ExecutorService es=Executors.newFixedThreadPool(2);
        //创建callable子类
        JiSuan js=new JiSuan(100);
        JiSuan js2=new JiSuan(200);
        //提交callable子类
        Future<Integer> f1=es.submit(js);
        Future<Integer> f2=es.submit(js2);
        //从future中获取返回值
        System.out.println(f1.get());
        System.out.println(f2.get());
        //关闭线程池
        es.shutdown();
    }

}
import java.util.concurrent.Callable;

public class JiSuan  implements Callable<Integer>{
    private Integer a ;
    JiSuan(Integer a){
        this.a=a ;
    }
    public Integer call(){
        int sum=0;
        for(int i=0;i<a;i++){
            sum+=i;
        }
        return null;
    }
}

 

posted on 2018-08-27 10:18  九九九九  阅读(189)  评论(0编辑  收藏  举报