• 常用的辅助类(必会)


    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,然后唤醒等待线程!

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

  • 相关阅读:
    闭包和回调函数
    人工神经网络算法的应用,人工神经网络算法步骤
    el-row和el-col在element ui中的注意点
    通讯录管理系统-C++课程设计
    go 包的引入
    “一人负债,全家背锅”,严厉打击信用卡套现欺诈
    数据库缓存一致性研究
    为什么使用Go语言做web开发?
    11.28~12.4日学习总结
    Python入门教程47:史上最齐全的第三方模块库
  • 原文地址:https://blog.csdn.net/qq_53374893/article/details/132939857