JUC学习-4_JUC辅助类_CountDownLatch-CyclicBarrier-Semaphore

减法计数器 CountDownLatch

// 减法 计数器
// 每次有线程调用 countDown() 数量-1 假设计数器变为0  countDownLatch.await()就会被唤醒 继续执行
public class CountDownLatchDemo {
    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()+"  Go out");
                countDownLatch.countDown();//-1
            }, String.valueOf(i)).start();
        }
        countDownLatch.await(); // 等待计数器归零 然后再向下执行
        System.out.println("关门");
    }
}

加法计数器 CyclicBarrier

public class CyclicBarrierDemo {
    public static void main(String[] args) {
        CyclicBarrier cyclicBarrier = new CyclicBarrier(7, () -> {
            System.out.println("召唤神龙");
        });
        for (int i = 1; i <= 7; i++) {
            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();
                }
            }, String.valueOf(i)).start();
        }

    }

}

Semaphore: 信号位

public class SemaphoreDemo {
    public static void main(String[] args) {
        // 线程数量
        Semaphore semaphore = new Semaphore(3);
        for (int i = 1; i <= 6; i++) {
            new Thread(() -> {
                try {
                    semaphore.acquire(); // 得到
                    System.out.println(Thread.currentThread().getName() + "抢到车位");
                    TimeUnit.SECONDS.sleep(2);
                    System.out.println(Thread.currentThread().getName() + "离开车位");

                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    semaphore.release();//释放
                }
            }, String.valueOf(i)).start();
        }
    }
}

作用: 多个共享资源互斥的使用 并发限流 控制最大的线程数

JUC学习-4_JUC辅助类_CountDownLatch-CyclicBarrier-Semaphore

上一篇:基于Maxmspjitter的基础【pixel shader】绘制模板Patcher


下一篇:学习Promise