public class ThreadTest {
public static void main(String[] args) throws InterruptedException, ExecutionException {
CountDownLatch latch = new CountDownLatch(10);
//存放future结果的集合
List<String> list = Collections.synchronizedList(new ArrayList<String>());
CallableThread callableThread = new CallableThread(latch,list);
ExecutorService executorService = Executors.newFixedThreadPool(10);
for (int i = 0; i < 10; i++) {
Future future = executorService.submit(callableThread);
// System.out.println(submit.get());//会造成线程阻塞
}
latch.await();//阻塞当前线程,直到计数器的值为0
//确保子线程都执行完了
if(list.size()>0){
for (String s : list) {
System.out.println(s);
}
}
Thread.sleep(1000);
System.out.println("子线程执行完,主线程开始执行!");
System.out.println("主线程已执行完毕!");
executorService.shutdown();
}
static class CallableThread implements Callable{
CountDownLatch latch;
List<String> list;
public CallableThread(CountDownLatch latch, List<String> list) {
this.latch = latch;
this.list = list;
}
@Override
public String call() throws Exception {
Thread.sleep(3000);
list.add(Thread.currentThread().getName()+"执行完了!");
latch.countDown();//线程执行完,countdownlatch锁-1
return Thread.currentThread().getName()+"执行完了!";
}
}
}
此情况适用于一次性开启多个线程调不同的接口采集数据,把数据汇总再统一return给前端;