# CountDownLatch demo演示数据分片多线程处理
package com.example.core.mydemo;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
/**
* 打印结果:
* begin
* 当前线程名称=pool-1-thread-1
* 业务逻辑多线程处理,可以按数据集合分片来处理
* 当前线程名称=pool-1-thread-2
* 业务逻辑多线程处理,可以按数据集合分片来处理
* 当前线程名称=pool-1-thread-5
* 业务逻辑多线程处理,可以按数据集合分片来处理
* 当前线程名称=pool-1-thread-6
* 业务逻辑多线程处理,可以按数据集合分片来处理
* 当前线程名称=pool-1-thread-7
* 业务逻辑多线程处理,可以按数据集合分片来处理
* 当前线程名称=pool-1-thread-3
* 业务逻辑多线程处理,可以按数据集合分片来处理
* 当前线程名称=pool-1-thread-4
* 业务逻辑多线程处理,可以按数据集合分片来处理
* 当前线程名称=pool-1-thread-8
* 业务逻辑多线程处理,可以按数据集合分片来处理
* 当前线程名称=pool-1-thread-9
* 业务逻辑多线程处理,可以按数据集合分片来处理
* 当前线程名称=pool-1-thread-10
* 业务逻辑多线程处理,可以按数据集合分片来处理
* finish
*
*
* 一个同步辅助类,在完成一组正在其他线程中执行的操作之前,它允许一个或多个线程一直等待。
* 用给定的计数 初始化 CountDownLatch。由于调用了 countDown() 方法,所以在当前计数到达零之前,await 方法会一直受阻塞。之后,会释放所有等待的线程,await 的所有后续调用都将立即返回。这种现象只出现一次——计数无法被重置。
*/
public class CountDownLatchTest {
public static void main(String[] args) {
ExecutorService executorService = Executors.newFixedThreadPool(10);
//splitLists 按集合来多线程处理数据
//通过CountDownLatch 的使用 我们控制了线程的执行顺序
CountDownLatch countDownLatch = new CountDownLatch(10);
System.out.println("begin");
for(int i= 0;i < 10; i++){
// System.out.println("i=" + i);
executorService.submit(() -> {
System.out.println("当前线程名称=" + Thread.currentThread().getName());
try {
//todo
System.out.println("业务逻辑多线程处理,可以按数据集合分片来处理");
} catch (Exception e) {
e.printStackTrace();
} finally {
countDownLatch.countDown();
System.out.println("countDown-" + Thread.currentThread().getName());
}
});
}
// 等待所有线程完毕
try {
//await() 方法具有阻塞作用
countDownLatch.await();
System.out.println("finish");
} catch (InterruptedException e) {
e.printStackTrace();
}
//结束
executorService.shutdown();
}
}