- CountDownLatch:一个同步辅助类,在完成一组正在其他线程中执行的操作之前,它允许一个或多个线程一直等待。
- CyclicBarrier:一个同步辅助类,它允许一组线程互相等待,直到到达某个公共屏障点
- Semaphore:一个计数信号量
- Exchanger:方便了两个共同操作线程之间的双向交换
CountDownLatch
CountDownLatch有一个正数计数器,countDown方法对计数器做减操作,await方法等待计数器达到0。所有await的线程都会阻塞直到计数器为0或者等待线程中断或者超时。
- public CountDownLatch(int count) 初始化计数器个数
- public void await() 计数器不为0时,线程一直阻塞
- public boolean await(long timeout, TimeUnit unit) 计数器不为0时或 指定的等待时间没有过去,线程一直阻塞
- public void countDown() 减少计数器的计数,如果计数达到零,则释放所有等待的线程。
- public long getCount() 返回当前计数
@Slf4j public class CountDownLatchDemo { private static final Integer THREAD_COUNT_NUM = 50; private static ExecutorService singleThreadPool; static { ThreadFactory namedThreadFactory = new ThreadFactoryBuilder().setNameFormat("jack").build(); singleThreadPool = new ThreadPoolExecutor( 10, 10, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(1024), namedThreadFactory, new ThreadPoolExecutor.AbortPolicy()); } /** * CountDownLatch是一个同步的辅助类,允许一个或多个线程,等待其他一组线程完成操作,再继续执行。 */ public static void main(String[] args) { log.info("准备50个线程"); LocalDateTime start = LocalDateTime.now(); CountDownLatch countDownLatch = new CountDownLatch(THREAD_COUNT_NUM); for (int i = 0; i < THREAD_COUNT_NUM; i++) { Integer index = i; singleThreadPool.execute(() -> { //设置线程名 String threadName = "线程" + index.toString(); log.info("thread {} is start...",threadName); try { //do something log.info("{} do something ...",threadName); } catch (Exception e){ log.error(e.getMessage()); }finally { countDownLatch.countDown(); } }); } //计数器必须大于等于0,只是等于0的时候,计数器就是0,调用await方法时不会阻塞当前线程。 try { countDownLatch.await(); } catch (InterruptedException e) { log.error(e.getMessage()); } //后续操作 LocalDateTime end = LocalDateTime.now(); Duration duration = Duration.between(start, end); log.info("执行时间为{}", duration.toMillis()); } }
CyclicBarrier
一个同步辅助类,它允许一组线程互相等待,直到到达某个公共屏障点 (common barrier point)。在涉及一组固定大小的线程的程序中,这些线程必须不时地互相等待,此时 CyclicBarrier 很有用。因为该 barrier 在释放等待线程后可以重用,所以称它为循环 的 barrier。CyclicBarrier 支持一个可选的 Runnable 命令,在一组线程中的最后一个线程到达之后(但在释放所有线程之前),该命令只在每个屏障点运行一次。若在继续所有参与线程之前更新共享状态,此屏障操作 很有用。
- public CyclicBarrier(int parties, Runnable barrierAction) 当await的数量到达了设定的数量后,首先执行该Runnable对象。
- public CyclicBarrier(int parties) 设置parties、count及barrierCommand属性。
- public int getParties() 返回跳过此障碍所需的参与方数量。
- public int await() 线程阻塞
- public int await(long timeout, TimeUnit unit) 线程阻塞
- public boolean isBroken() 查询此屏障是否处于损坏状态
- public void reset() 重置屏障
- public int getNumberWaiting()
@Slf4j public class CyclicBarrierDemo { private static final Integer THREAD_COUNT_NUM = 50; private static ExecutorService singleThreadPool; static { ThreadFactory namedThreadFactory = new ThreadFactoryBuilder().setNameFormat("jack").build(); singleThreadPool = new ThreadPoolExecutor( 50, 50, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(1024), namedThreadFactory, new ThreadPoolExecutor.AbortPolicy()); } /** * CyclicBarrier是一个同步的辅助类,允许一组线程相互之间等待,达到一个共同点,再继续执行。 */ public static void main(String[] args) { //循环屏障1 准备50给线程集结完毕 //当await的数量到达了设定的数量后,首先执行该Runnable对象。 CyclicBarrier cyclicBarrier = new CyclicBarrier(THREAD_COUNT_NUM, () -> { log.info("50个线程准备完毕"); //50个线程集结完毕后开始工作 CyclicBarrier cyclicBarrier1 = new CyclicBarrier(THREAD_COUNT_NUM, () -> log.info("50个线程工作完毕")); for (int i = 0; i < THREAD_COUNT_NUM; i++) { Integer index = i; singleThreadPool.execute(() -> { log.info("第 {} 个线程开始工作", index); try { //通知屏障,我已到达 cyclicBarrier1.await(); } catch (InterruptedException | BrokenBarrierException e) { e.printStackTrace(); } }); } }); for (int i = 0; i < THREAD_COUNT_NUM; i++) { Integer index = i; singleThreadPool.execute(() -> { log.info("第 {} 个线程已经准备完毕", index); try { //通知屏障,我已到达 cyclicBarrier.await(); } catch (InterruptedException | BrokenBarrierException e) { e.printStackTrace(); } }); } } }
Semaphore
Semaphore是一个计数器,在计数器不为0的时候对线程就放行,一旦达到0,那么所有请求资源的新线程都会被阻塞,包括增加请求到许可的线程,也就是说Semaphore不是可重入的。每一次请求一个许可都会导致计数器减少1,同样每次释放一个许可都会导致计数器增加1,一旦达到了0,新的许可请求线程将被挂起。
- public void acquire() 从此信号量获取一个许可,在提供一个许可前一直将线程阻塞,否则线程被中断。
- public void release() 释放一个许可,将其返回给信号量。
- public int availablePermits() 返回此信号量中当前可用的许可数。
- public final boolean hasQueuedThreads() 查询是否有线程正在等待获取
@Slf4j public class SemaphoreDemo { private static final Integer THREAD_COUNT_NUM = 50; private static final Integer MAX_THREAD_COUNT_NUM = 10; private static ExecutorService singleThreadPool; static { ThreadFactory namedThreadFactory = new ThreadFactoryBuilder().setNameFormat("jack").build(); singleThreadPool = new ThreadPoolExecutor( 50, 50, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(1024), namedThreadFactory, new ThreadPoolExecutor.AbortPolicy()); } public static void main(String[] args) { Semaphore semaphore = new Semaphore(MAX_THREAD_COUNT_NUM); for (int i = 0; i < THREAD_COUNT_NUM; i++) { Integer index = i; //模拟线程执行时间 try { Thread.sleep(100); } catch (InterruptedException e) { log.error(e.getMessage()); } singleThreadPool.execute(() -> { try { //获得许可证 semaphore.acquire(); Thread.sleep(10000); log.info("Thread {} do something", index); //归还许可证 semaphore.release(); } catch (InterruptedException e) { log.error(e.getMessage()); } }); } } }
Exchanger
- public V exchange(V x)
- public V exchange(V x, long timeout, TimeUnit unit)
@Slf4j public class ExchangerDemo { private static final Integer THREAD_COUNT_NUM = 50; private static ExecutorService singleThreadPool; static { ThreadFactory namedThreadFactory = new ThreadFactoryBuilder().setNameFormat("jack").build(); singleThreadPool = new ThreadPoolExecutor( 10, 10, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(1024), namedThreadFactory, new ThreadPoolExecutor.AbortPolicy()); } public static void main(String[] args) { Exchanger<String> exchanger = new Exchanger<>(); singleThreadPool.execute(() -> { try { //A录入记录 String A = "A的记录"; exchanger.exchange(A); } catch (Exception e) { log.error(e.getMessage()); } }); singleThreadPool.execute(() -> { try { //B录入记录 String B = "B的记录"; String A = exchanger.exchange("B"); log.info("a和b的数据是否一致{},A录入的是{},B录入的是{}", A.equals(B), A, B); } catch (Exception e) { log.error(e.getMessage()); } }); } }