线程池等待一定数目的线程执行完毕之后返回结果

<span style="font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);">最近在优化代码,看见很多可以并行操作的代码被写成了for循环串行执行.所以就有想写一个小小的工具类的意图.</span>

主要作用是.批量执行一定量的线程,线程带返回值.且这些线程都执行完毕才进行返回.不然主线程一直阻塞.

查看线程池的接口ExecutorService 觉得invokeAll这个方法也许能达到我想做的事情


上图是jdk中的注释.

直接上代码


package com.joe.core.executor;


import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;


public class BdpExecutor {


public static ExecutorService cachedThreadPool = Executors
.newFixedThreadPool(20);


public static void main(String[] args) throws Exception {
ArrayList<Mythread> list = new ArrayList<Mythread>();
for (int i = 2; i < 7; i++) {
// Future<String> fu = cachedThreadPool.submit(new Mythread());
// String string = fu.get();
// System.out.println(string+i);
list.add(new Mythread(i*1000));
}
List<Future<String>> futureList = cachedThreadPool.invokeAll(list);
System.out.println("over-------");
for (Future<String> fu : futureList) {
System.out.println(fu.get());
}
}


static class Mythread implements Callable<String> {
int i = 200;


public Mythread(int i) {
this.i = i;
}


@Override
public String call() throws Exception {
System.out.println("线程启动---" + Thread.currentThread().getName()
+ new Date());
try {
Thread.sleep(i);
System.out.println("休眠了"+i+"秒 线程结束---" + Thread.currentThread().getName()
+ new Date());
} catch (InterruptedException e) {
e.printStackTrace();
}
return "sucess"+i;
}
}


}


稍微解释一下,我main方法中启动了5个线程,每个线程依次休眠了几秒.最后返回个sucess.

附上运行结果

线程启动---pool-1-thread-5Wed Jul 13 13:27:03 CST 2016
线程启动---pool-1-thread-1Wed Jul 13 13:27:03 CST 2016
线程启动---pool-1-thread-2Wed Jul 13 13:27:03 CST 2016
线程启动---pool-1-thread-3Wed Jul 13 13:27:03 CST 2016
线程启动---pool-1-thread-4Wed Jul 13 13:27:03 CST 2016
休眠了2000秒 线程结束---pool-1-thread-1Wed Jul 13 13:27:05 CST 2016
休眠了3000秒 线程结束---pool-1-thread-2Wed Jul 13 13:27:06 CST 2016
休眠了4000秒 线程结束---pool-1-thread-3Wed Jul 13 13:27:07 CST 2016
休眠了5000秒 线程结束---pool-1-thread-4Wed Jul 13 13:27:08 CST 2016
休眠了6000秒 线程结束---pool-1-thread-5Wed Jul 13 13:27:09 CST 2016
over-------
sucess2000
sucess3000
sucess4000
sucess5000
sucess6000


版权声明:本文为qqpy789原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。