线程池创建提交任务——java

用线程池分别计算1-100和1-200的值

public static void main(String[] args)throws Exception{
        // 创建线程池对象并指定线程数量
        ExecutorService tp = Executors.newFixedThreadPool(2);

        // 提交两个任务
        Future<Integer> f1 =  tp.submit(new CalcTask(100));
        Future<Integer> f2 =  tp.submit(new CalcTask(200));

        System.out.println(f1.get()); // 5050
        System.out.println(f2.get()); // 20100
        // 销毁线程池
        tp.shutdown();
}
public class CalcTask implements Callable<Integer>{

    private int  num;

    public CalcTask(int num) {
        this.num = num;
    }

    @Override
    public Integer call() throws Exception {
        // 定义求和变量
        int sum = 0;
        for (int i = 1; i <= num ; i++) {
            sum += i;
        }
        return sum;
    }
}

  

猜你喜欢

转载自www.cnblogs.com/leonHQ/p/9489772.html