• 常用的辅助类(必会)


    1.CountDownLatch

    1. package com.kuang.add;
    2. import java.util.concurrent.CountDownLatch;
    3. //计数器 减法
    4. public class CountDownLatchDemo {
    5. public static void main(String[] args) throws InterruptedException {
    6. //总数是6,必须要执行任务的时候,再使用
    7. CountDownLatch countDownLatch = new CountDownLatch(6);
    8. for (int i = 0; i < 6; i++) {
    9. int finalI = i;
    10. new Thread(()->{
    11. try {
    12. System.out.println(Thread.currentThread().getName()+" Go Out");
    13. } catch (Exception e) {
    14. e.printStackTrace();
    15. } finally {
    16. countDownLatch.countDown();
    17. }
    18. },String.valueOf(i)).start();
    19. }
    20. countDownLatch.await();//等待计数器归零,然后再向下执行
    21. System.out.println("close Door");
    22. }
    23. }

    2.CyclicBarrier

    1. package com.kuang.add;
    2. import java.util.concurrent.BrokenBarrierException;
    3. import java.util.concurrent.CyclicBarrier;
    4. public class CyclicBarrierDemo {
    5. public static void main(String[] args) {
    6. /**
    7. * 集齐7颗龙珠 召唤神龙
    8. */
    9. //召唤龙珠的线程
    10. CyclicBarrier cyclicBarrier= new CyclicBarrier(7,()->{
    11. System.out.println("召唤神龙成功");
    12. });
    13. for (int i = 0; i < 6; i++) {
    14. int finalI = i;
    15. new Thread(()->{
    16. System.out.println(Thread.currentThread().getName()+"收集了"+ finalI+"个龙珠");
    17. try {
    18. cyclicBarrier.await();//等待
    19. } catch (InterruptedException e) {
    20. e.printStackTrace();
    21. } catch (BrokenBarrierException e) {
    22. e.printStackTrace();
    23. }
    24. }).start();
    25. }
    26. }
    27. }

     

    3.Semaphore

    Semaphore :信号量

    1. package com.kuang.add;
    2. import java.util.concurrent.Semaphore;
    3. import java.util.concurrent.TimeUnit;
    4. public class SemaphoreDemo {
    5. public static void main(String[] args) {
    6. //线程数量,停车位!
    7. Semaphore semaphore = new Semaphore(3);
    8. for (int i = 0; i < 6; i++) {
    9. new Thread(()->{
    10. //acquire()得到许可
    11. try {
    12. semaphore.acquire();
    13. System.out.println(Thread.currentThread().getName()+"抢到车位");
    14. TimeUnit.SECONDS.sleep(2);
    15. System.out.println(Thread.currentThread().getName()+"离开车位");
    16. } catch (InterruptedException e) {
    17. e.printStackTrace();
    18. }finally {
    19. semaphore.release();//release() 释放
    20. }
    21. },String.valueOf(i)).start();
    22. }
    23. }
    24. }

    原理:

    semaphore.acquire(); 获得,假设如果已经满了,等待,等待被释放为止!
    semaphore.release(); 释放,会将当前的信号量释放+1,然后唤醒等待线程!

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

  • 相关阅读:
    企业直播:会畅通讯、好视通、飞书见仁见智
    蓝桥杯嵌入式第二篇配置按键
    算法竞赛入门【码蹄集进阶塔335题】(MT2271-2275)
    ggrcs 包2.4绘图实际操作演示(1)
    【量化交易】量化因子 基础科目衍生类因子计算
    [附源码]java毕业设计圆梦山区贫困学生助学系统
    MYSQL -- Binlog数据还原
    java计算机毕业设计springboot+vue教师支教系统(源码+系统+mysql数据库+Lw文档)
    Python3操作文件系列(二):文件数据读写|二进制数据读写
    Vue脚手架的搭建
  • 原文地址:https://blog.csdn.net/qq_53374893/article/details/132939857