ExecutorService & Callable实现多线程执行并取得每个线程的值

用ExecutorService运行多线程, 实现Callable接口,执行并取得每个线程的值的场景,如下图所示:
ExecutorService & Callable实现多线程执行并取得每个线程的值_第1张图片

代码如下:
package com.xue.gang;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;

public class FutureTaskRunnerMutiExecutor {

public static void main(String args[]) throws InterruptedException, ExecutionException{

    int size = 100;
    List<FutureTask>  list= new ArrayList<FutureTask>();
    ExecutorService executorService = Executors.newCachedThreadPool();
    //ExecutorService executorService = Executors.newFixedThreadPool(size);
    //协调线程之间
    CountDownLatch countDownLatch = new CountDownLatch(size);

    for(int i =1;i<=size;i++){
        System.out.println("---------run index is : " + i);
        FutureTask futureTask = new FutureTask<Object>(new RunnerCallable(i,countDownLatch));
        executorService.execute(futureTask);
        list.add(futureTask);
    }

    countDownLatch.await();

    for(FutureTask ft:list){
        System.out.println("=============ft get is : " + ft.get());
    }
    //如果不关闭,需要等待超时.
    executorService.shutdown();
}

}
/*业务代码/
class RunnerCallable implements Callable{

private int sumto=0;
private CountDownLatch countDownLatch;


public Object call() throws Exception {
    int sum=0;
    for(int i =0;i<this.sumto;i++){
        sum +=i;
        System.out.println(Thread.currentThread().getId() + "_index is : " + i);
    }
    //减一
    countDownLatch.countDown();
    return  sum;
}


public RunnerCallable(int sumto, CountDownLatch countDownLatch) {
    super();
    this.sumto = sumto;
    this.countDownLatch = countDownLatch;
}

}

你可能感兴趣的:(java,CountDownLatch,executorService)