写一个程序,在线程池中提交多个任务,每个任务最终都有一个执行结果,需求是对每个任务的执行结果进行汇总(样例中是把结果加在一起)。这里使用线程池的submit方法和Future实现。
定义一个任务类
import java.util.Random;
import java.util.concurrent.Callable;
/**
* 创建人:yang.liu
* 创建时间:2019/8/10 14:29
* 版本:1.0
* 内容描述:计算用户等级积分的任务
*/
class PointTask implements Callable<Integer> {
private int customerId;
// customerId是假设每个任务都需要设置执行的参数。
public PointTask(int customerId) {
this.customerId = customerId;
}
@Override
public Integer call() throws Exception {
//模拟任务执行时间
Thread.sleep(new Random().nextInt(1000) + 1);
System.out.println("计算用户积分中。。。");
// return new Random().nextInt(10) + 1;
// 返回1便于测试,确认任务结果。
return 1;
}
}
实现多个任务的创建、执行,合并任务的执行结果
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.*;
/**
* 创建人:yang.liu
* 创建时间:2019/8/10 14:09
* 版本:1.0
* 内容描述:通过Future实现多个任务结果汇总
*/
public class TestFuture {
public static void main(String[] args) throws InterruptedException, ExecutionException {
int taskNum = 10000;
ExecutorService executor = Executors.newCachedThreadPool();
List<Future<Integer>> pointTaskFutureList = new ArrayList<>(taskNum);
for (int i = 0; i < taskNum; i++) {
// 提交任务,任务的执行由线程池去调用执行并管理。
// 这里获取结果任务的Future,并放到list中,供所有任务提交完后,通过每个任务的Future判断执行状态和结果。
Future<Integer> future = executor.submit(new PointTask(i + 1));
pointTaskFutureList.add(future);
}
int total = 0; // 总计算结果
int done = 0; //完成任务的数量
while (!pointTaskFutureList.isEmpty()) {
Iterator<Future<Integer>> iter = pointTaskFutureList.iterator();
while (iter.hasNext()) {
Future<Integer> next = iter.next();
if (next.isDone()) {
done++;
Integer res = next.get();
total += res;
iter.remove();
}
}
System.out.println("完成任务量:" + done + " 此时计算结果为:" + total);
// 停留一会,避免一直循环。
Thread.sleep(1000L);
}
System.out.println("执行完成后,完成任务量:" + done + " 此时计算结果为:" + total);
executor.shutdown();
}
}
/**
* 本人能力有限,难免考虑不周,对于不好的地方。欢迎评论、留言、发表看法。谢谢!
*/