[原創] JAVA 遞歸線程池測試 ExecutorService / ForkJoinPool

 

 

測試工具使用遞歸的方式獲取子進程的Msg消息,目前有2種經常使用的ExecutorService / ForkJoinPooljava

爲了測試哪一種效果較好,咱們來寫個測試Demo,循環5555555次+1(加鎖),統計每種執行耗時工具

 

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

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

 

TestData:5555555 , RunTime:1543 ms :ExecutorService executorPoolspa

TestData:5555555 , RunTime:746 ms :ForkJoinPool forkJoinPool線程

結果很明顯,遞歸線程池使用ForkJoinPool更佳,2倍的執行效率3d

 

測試流程圖code

 

 

 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 }
相關文章
相關標籤/搜索