CountDownLatch 倒计时锁存器
CountDownLatch,其实就是一个计数器来,初始值为线程的数量。每执行一个线程,计数器减1,当计数器到达0时,即所有的线程都执行结束,恢复主线程执行任务。
package com.chengjiang.common.core.countDownLatch;
import java.util.concurrent.*;
/**
* 多线程并发控制工具 CountDownLatch 测试
*
* @author zhao-cj
*/
public class CountDownLatchDemo {
public static void main(String[] args) {
// 线程数
int threadNum = 10;
CountDownLatch countDownLatch = new CountDownLatch(threadNum);
ExecutorService service = new ThreadPoolExecutor(5, 10, 0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>(30));
for (int i = 0; i < threadNum; i++) {
service.submit(() -> {
try {
System.out.println("Thread " + Thread.currentThread().getName() + " is performing computation.");
Thread.sleep(2000L);
System.out.println("Thread " + Thread.currentThread().getName() + " has completed computation.");
countDownLatch.countDown();
} catch (InterruptedException e) {
e.printStackTrace();
}
});
}
try {
countDownLatch.await();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
service.shutdown();
}
System.out.println("所有子线程执行结束,开始后续工作....");
}
}
CyclicBarrier 循环屏障
CyclicBarrier 可以理解为循环栅栏,也就是说这个计数器可以循环反复使用。如果我们将计数器设置为 10 ,那么湊齐第一批 10 个线程后,计数器就会归零,接着凑齐下一批 10 个线程,这就是循环栅栏内在的含义。
package com.chengjiang.common.core.cyclicBarrier;
import java.util.concurrent.*;
/**
* 多线程并发控制工具 CyclicBarrier 测试
*
* @author zhao-cj
*/
public class CyclicBarrierDemo {
public static void main(String[] args) {
// 总任务数
int totalThreadNum = 9;
// 单次循环任务数
int threadNum = 3;
// 线程池
ExecutorService service = new ThreadPoolExecutor(threadNum, 20, 0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>(30));
// 线程执行计数器
CyclicBarrier cyclicBarrier = new CyclicBarrier(threadNum + 1, () -> {
System.out.println("单次循环内子线程执行结束,开始后续工作....");
});
// 开始执行任务
for (int i = 1; i <= totalThreadNum; i++) {
service.execute(() -> {
try {
System.out.println("Thread " + Thread.currentThread().getName() + " is performing computation.");
Thread.sleep(2000L);
System.out.println("Thread " + Thread.currentThread().getName() + " has completed computation.");
// 告知计数器,已执行
cyclicBarrier.await();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (BrokenBarrierException e) {
e.printStackTrace();
}
});
if (i % threadNum == 0) {
try {
cyclicBarrier.await();
} catch (BrokenBarrierException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
service.shutdown();
}
}
CyclicBarrier与CountDownLatch的区别:
- CyclicBarrier比CountDownLatch稍微复杂
- 两者构造参数不同:CyclicBarrier比CountDownLatch多一个两个参数的构造函数
- 两者初始值不同:CyclicBarrier比CountDownLatch的初始值参数大1,原因是CyclicBarrier.await()除了在子线程中调用外还要调用一次。
- 两者计数规则不同:CyclicBarrier的计数是调用await()的次数,CountDownLatch的计数是调用countDown()的次数;
- 两者使用次数不同:CyclicBarrier可以循环使用,而CountDownLatch不是循环使用的。