JAVA 递归线程池测试 ExecutorService / ForkJoinPool

JAVA 递归线程池测试 ExecutorService / ForkJoinPool_第1张图片

 

测试工具使用递归的方式获取子进程的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倍的执行效率

 

测试流程图

 

JAVA 递归线程池测试 ExecutorService / ForkJoinPool_第2张图片

 

 

package test;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ForkJoinPool;

/**
 *
 * @author weimjsam
 */
public class TestThrad {

    public int addNum = 0;

    //get cpu 
    int nCpu = Runtime.getRuntime().availableProcessors();

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

    private void TaskPush(int iTestAdd) {
        CompletableFuture.runAsync(() -> {

            for (int i = 0; i < nCpu; i++) {
                CompletableFuture.runAsync(() -> TestRun(iTestAdd), forkJoinPool);
            }

        }, taskPush);
    }

    private void TestRun(int iTestAdd) {
        CompletableFuture.runAsync(() -> TestAdd(iTestAdd), forkJoinPool)
                .thenRun(() -> CheckOver(iTestAdd));
    }

    private void TestAdd(int iTestAdd) {
        synchronized (this) {
            if (addNum < iTestAdd) {
                addNum = addNum + 1;
            }
        }
    }

    private void CheckOver(int iTestAdd) {
        if (addNum < iTestAdd) {
            TestRun(iTestAdd);
        }
    }

    public void Test(int iTestMax) {
        TaskPush(iTestMax);
    }

}

 

 

 

 

 

 

 

 

 

https://dwz.cn/0eWL012M

你可能感兴趣的:(经验分享)