import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;
import java.util.logging.Logger;
public class CountDownLatchTest {
//创建同步器
private static CountDownLatch countDownLatch = new CountDownLatch(5);
public static void main(String[] args) throws InterruptedException, ExecutionException {
//记录并打印开始时间
long start = System.currentTimeMillis();
System.out.println("startTima:"+start);
//分拆任务后返回结果存放集合
List<String> resList = new ArrayList<>();
//创建固定大小线程池
ExecutorService executorService = Executors.newFixedThreadPool(5);
//创建多个Callable接口的实现
CallAble can5 = new CallAble(4, countDownLatch, "我是线程5");
CallAble can4 = new CallAble(4, countDownLatch, "我是线程4");
CallAble can3 = new CallAble(3, countDownLatch, "我是线程3");
CallAble can2 = new CallAble(2, countDownLatch, "我是线程2");
CallAble can1 = new CallAble(1, countDownLatch, "我是线程1");
//提交线程任务
Future<List<String>> submit5 = executorService.submit(can5);
Future<List<String>> submit4 = executorService.submit(can4);
Future<List<String>> submit3 = executorService.submit(can3);
Future<List<String>> submit2 = executorService.submit(can2);
Future<List<String>> submit1 = executorService.submit(can1);
//等待所有线程返回结果
countDownLatch.await();
//将子线程结果添加到返回值集合
resList.addAll(submit5.get());
resList.addAll(submit4.get());
resList.addAll(submit3.get());
resList.addAll(submit2.get());
resList.addAll(submit1.get());
//销毁线程池
executorService.shutdown();
System.out.println("+++++++++++++++");
//打印子线程结果
resList.forEach(temm -> System.out.println(temm));
//打印结果集大小
System.out.println("temList.size:"+resList.size());
//记录并打印结束时间
long end = System.currentTimeMillis();
System.out.println("endtime:"+end);
System.out.println("总耗时:"+(end-start)/1000+"s");
}
}
//实现callable接口的实现类
class CallAble implements Callable<List<String>> {
Logger log = Logger.getLogger("log");
private int nun;
//定义同步量
private CountDownLatch cdl;
//定义线程名称
private String name;
//构造方法
public CallAble(int num, CountDownLatch countDownLatch, String name) {
this.nun = num;
this.cdl = countDownLatch;
this.name = name;
}
@Override
//实现callable接口call方法
public List<String> call() throws Exception {
//定义返回结果
List<String> list = new ArrayList<>();
System.out.println(Thread.currentThread().getName());
try {
//业务操作或者数据库的操作
list.add(String.valueOf(this.nun));
list.add(name);
//程序休眠num秒
Thread.sleep(this.nun*1000);
System.out.println(name);
// log.info(name);
} finally {
//计数器减一
cdl.countDown();
}
return list;
}
}