• 如何使用Semaphore和CompletableFuture搭配实现控制线程并发数量并等待所有线程执行完成之后在执行其它操作


    代码示例:

    1. public static void main(String[] args) throws InterruptedException {
    2. ExecutorService executor = Executors.newFixedThreadPool(4);
    3. Semaphore semaphore = new Semaphore(2);
    4. try {
    5. CompletableFuture futureA = CompletableFuture.supplyAsync(() -> {
    6. try {
    7. semaphore.acquire(); // 获取信号量,限制并发数
    8. // 调用外部接口 A
    9. System.out.println("A进入车库");
    10. Thread.sleep(9000);
    11. System.out.println("A离开车位");
    12. return "A";
    13. } catch (InterruptedException e) {
    14. throw new RuntimeException(e);
    15. } finally {
    16. semaphore.release(); // 释放信号量
    17. }
    18. }, executor);
    19. CompletableFuture futureB = CompletableFuture.supplyAsync(() -> {
    20. try {
    21. semaphore.acquire(); // 获取信号量,限制并发数
    22. // 调用外部接口 B
    23. System.out.println("B进入车库");
    24. Thread.sleep(9000);
    25. System.out.println("B离开车位");
    26. return "B";
    27. } catch (InterruptedException e) {
    28. throw new RuntimeException(e);
    29. } finally {
    30. semaphore.release(); // 释放信号量
    31. }
    32. }, executor);
    33. CompletableFuture futureC = CompletableFuture.supplyAsync(() -> {
    34. try {
    35. semaphore.acquire(); // 获取信号量,限制并发数
    36. // 调用外部接口 C
    37. System.out.println("C进入车库");
    38. Thread.sleep(9000);
    39. System.out.println("C离开车位");
    40. return "C";
    41. } catch (InterruptedException e) {
    42. throw new RuntimeException(e);
    43. } finally {
    44. semaphore.release(); // 释放信号量
    45. }
    46. }, executor);
    47. CompletableFuture futureD = CompletableFuture.supplyAsync(() -> {
    48. try {
    49. semaphore.acquire(); // 获取信号量,限制并发数
    50. // 调用外部接口 D
    51. System.out.println("D进入车库");
    52. Thread.sleep(9000);
    53. System.out.println("D离开车位");
    54. return "D";
    55. } catch (InterruptedException e) {
    56. throw new RuntimeException(e);
    57. } finally {
    58. semaphore.release(); // 释放信号量
    59. }
    60. }, executor);
    61. CompletableFuture combinedFuture = CompletableFuture.allOf(futureA, futureB, futureC, futureD);
    62. combinedFuture.thenAccept(result -> {
    63. // 汇总数据
    64. String dataA = futureA.join();
    65. String dataB = futureB.join();
    66. String dataC = futureC.join();
    67. String dataD = futureD.join();
    68. String combinedData = dataA + dataB + dataC + dataD;
    69. System.out.println(combinedData);
    70. });
    71. } catch (Exception exception) {
    72. exception.printStackTrace();
    73. }
    74. executor.shutdown();
    75. }

    打印结果:

  • 相关阅读:
    Maven-依赖管理机制
    车联网安全集智联盟正式成立
    Go — 相关依赖对应的exe
    Xcode15 framework ‘CoreAudioTypes‘ not found
    ansible的配置及其应用
    Databend 开源周报第 116 期
    【每日一题】最大矩形
    SCI论文写作(二) | SCI论文的引言(Introduction)部分
    【前端开发基础知识&快速入门】
    设计师找灵感,这5个网站就够了
  • 原文地址:https://blog.csdn.net/XikYu/article/details/132904304