zoukankan      html  css  js  c++  java
  • [原创] JAVA 递归线程池测试 ExecutorService / ForkJoinPool

    测试工具使用递归的方式获取子进程的Msg消息,目前有2种常用的ExecutorService / ForkJoinPool

    为了测试哪种效果较好,我们来写个测试Demo,循环5555555次+1(加锁),统计每种执行耗时

    int nCpu = Runtime.getRuntime().availableProcessors();

    ExecutorService executorPool  = Executors.newFixedThreadPool(nCpu);
    ForkJoinPool forkJoinPool = new ForkJoinPool(nCpu);

    TestData:5555555 , RunTime:1543 ms :ExecutorService executorPool

    TestData:5555555 , RunTime:746 ms :ForkJoinPool forkJoinPool

    结果很明显,递归线程池使用ForkJoinPool更佳,2倍的执行效率

    测试流程图

     1 package test;
     2 
     3 import java.util.concurrent.CompletableFuture;
     4 import java.util.concurrent.ExecutorService;
     5 import java.util.concurrent.Executors;
     6 import java.util.concurrent.ForkJoinPool;
     7 
     8 /**
     9  *
    10  * @author weimjsam
    11  */
    12 public class TestThrad {
    13 
    14     public int addNum = 0;
    15 
    16     //get cpu 
    17     int nCpu = Runtime.getRuntime().availableProcessors();
    18 
    19     //Thread
    20     ExecutorService taskPush = Executors.newFixedThreadPool(nCpu);
    21     ExecutorService executorPool = Executors.newFixedThreadPool(nCpu);
    22     ForkJoinPool forkJoinPool = new ForkJoinPool(nCpu);
    23 
    24     private void TaskPush(int iTestAdd) {
    25         CompletableFuture.runAsync(() -> {
    26 
    27             for (int i = 0; i < nCpu; i++) {
    28                 CompletableFuture.runAsync(() -> TestRun(iTestAdd), forkJoinPool);
    29             }
    30 
    31         }, taskPush);
    32     }
    33 
    34     private void TestRun(int iTestAdd) {
    35         CompletableFuture.runAsync(() -> TestAdd(iTestAdd), forkJoinPool)
    36                 .thenRun(() -> CheckOver(iTestAdd));
    37     }
    38 
    39     private void TestAdd(int iTestAdd) {
    40         synchronized (this) {
    41             if (addNum < iTestAdd) {
    42                 addNum = addNum + 1;
    43             }
    44         }
    45     }
    46 
    47     private void CheckOver(int iTestAdd) {
    48         if (addNum < iTestAdd) {
    49             TestRun(iTestAdd);
    50         }
    51     }
    52 
    53     public void Test(int iTestMax) {
    54         TaskPush(iTestMax);
    55     }
    56 
    57 }
  • 相关阅读:
    漫谈PID——实现与调参
    匿名上位机的使用(51版)
    #if 和 #ifdef 条件编译注意
    关于HC04超声波模块测距的思考(51版)
    关于C语言文件操作
    C语言实现简易2048小游戏
    关于OELD屏显示电池电量的简易方法
    使用notepad++作为keil的外部编辑器
    2017年个人总结
    数据存入文件
  • 原文地址:https://www.cnblogs.com/weimjsam/p/10468792.html
Copyright © 2011-2022 走看看