蘇阿細 - Semaphore
type: channel
link: https://www.wangchouchou.com/tag/Semaphore/
items: JUC常用的辅助类

JUC常用的辅助类
type: item
date: 2021-02-12T14:18:00+00:00
description: 常用的辅助类1、CountDownLatch允许一个或多个线程等待其他线程完成操作package com.sw.assist; import java.util.concurrent.CountDownLatch; /** * @Author suaxi * @Date 2021/2/12 21:41 * * assist 辅助类 */ //减法计数器 public class CountDownLatchTest { public static void main(String[] args) throws InterruptedException { //总数为6 CountDownLatch countDownLatch = new CountDownLatch(6); for (int i = 1; i <= 6; i++) { new Thread(() -> { System.out.println(Thread.currentThread().getName() + "--->走出教室"); countDownLatch.countDown(); //数量减1 }, String.valueOf(i)).start(); } countDownLatch.await(); //等待计数器归零，再向下执行 System.out.println("学生放学离开教室，班长锁门"); } } CountDownLatch原理：countDownLatch.countDown(); //数量减1countDownLatch.await(); //等待计数器归零，再向下执行执行方法，线程调用countDown();，使计数器数量减1，当计数器变为0时，countDownLatch.await();就会被唤醒，继续执行方法2、CyclicBarrier实现一组线程互相等待，当所有的线程都到达某个屏障点后再进行后续的操作package com.sw.assist; import java.util.concurrent.BrokenBarrierException; import java.util.concurrent.CyclicBarrier; /** * @Author suaxi * @Date 2021/2/12 21:56 */ //加法计数器 public class CyclicBarrierTest { public static void main(String[] args) { //10个学生都到教室后，老师才开始上课 CyclicBarrier cyclicBarrier = new CyclicBarrier(10, () -> { System.out.println("孙老师开始上课"); }); for (int i = 1; i <= 10; i++) { //注：lambda表达式不能直接操作for循环中的i，它只是简化了new对象的过程 final int temp = i; new Thread(() -> { System.out.println(Thread.currentThread().getName() + "学生" + temp + "进入教室"); try { cyclicBarrier.await(); //等待 } catch (InterruptedException e) { e.printStackTrace(); } catch (BrokenBarrierException e) { e.printStackTrace(); } }).start(); } } } 3、Semaphore可以控制同时访问线程的个数package com.sw.assist; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; /** * @Author suaxi * @Date 2021/2/12 22:10 */ //停车位 public class SemaphoreTest { public static void main(String[] args) { //线程数量：提供3个停车位 Semaphore semaphore = new Semaphore(3); for (int i = 1; i <= 6; i++) { new Thread(() -> { try { semaphore.acquire(); //得到 System.out.println(Thread.currentThread().getName() + "---驶入停车位"); Time…