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倍的执行效率

 

测试流程图

 

 

 

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值