用ExecutorService運行多線程, 實現Callable接口,執行並取得每一個線程的值的場景,以下圖所示: java
代碼以下: 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;this
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<Object>{code
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; }
}接口