package org.ado.test;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class ExecutorServiceDemo {
public static void main(String[] args) throws InterruptedException, ExecutionException {
List<CallableTask> lstCallableTask = getExecuteTaskList();
ExecutorService executorService = getExecutorService();
List<Future<String>> futures = getTaskResultList(executorService, lstCallableTask);
printResult(futures);
executorService.shutdown();
}
private static List<CallableTask> getExecuteTaskList(){
List<CallableTask> lstCallableTask = new ArrayList<CallableTask>();
String[] strParams = {"1","2","3","4","5"};
for (int i = 0; i < strParams.length; i++) {
lstCallableTask.add(new CallableTask(strParams[i]));
}
return lstCallableTask;
}
private static List<Future<String>> getTaskResultList(ExecutorService executorService, List<CallableTask> lstCallableTask){
List<Future<String>> futures = new ArrayList<Future<String>>();
for (Iterator<CallableTask> iterator = lstCallableTask.iterator(); iterator.hasNext();) {
CallableTask callableTask = (CallableTask) iterator.next();
futures.add(executorService.submit(callableTask));
}
return futures;
}
private static void printResult(List<Future<String>> futures) throws InterruptedException, ExecutionException{
for (Iterator<Future<String>> iterator = futures.iterator(); iterator.hasNext();) {
Future<String> future = (Future<String>) iterator.next();
System.out.println(future.get());
}
}
private static ExecutorService getExecutorService(){
return (ExecutorService) Executors.newFixedThreadPool(5);
}
static class CallableTask implements Callable<String>{
private String param;
CallableTask(String param){
this.param = param;
}
@Override
public String call() throws Exception {
Thread.sleep(5000);
return "result:" + param;
}
}
}
ExecutorService
最新推荐文章于 2024-09-19 13:19:42 发布