ExecutorService

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;
}

}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值