程序创建的线程比请求的多

Program creates more threads than requested

我正在尝试实现并行合并排序。

但我遇到了一个问题:

代码:

            Thread tl, tr;

            tl = new Thread(new MergeSortRunner(left, threadCount - 1));
            tr = new Thread(new MergeSortRunner(right, threadCount - 1));

数据正在排序,但使用的线程数与Runtime.getRuntime().availableProcessors()不对应。

输出:

.
. 
. 
Thread-190
Thread-229
Thread-171
Thread-183
Thread-191
Thread-187
[1, 1, 2, 3, 3, 4, 6, 6, 8, 9, 10, 13, 13, 14, 15, 16, 18, 20, 21, 23, 23, 23, 24, 25, 29, 29, 30, 35, 35, 37, 38, 39, 41, 41, 42, 42, 42, 42, 43, 44, 46, 46, 47, 49, 49, 50, 51, 52, 52, 52, 54, 55, 58, 58, 59, 59, 60, 61, 61, 62, 62, 63, 64, 64, 64, 64, 65, 66, 66, 69, 70, 70, 72, 73, 73, 74, 74, 75, 75, 76, 78, 82, 84, 86, 87, 87, 88, 88, 91, 91, 93, 93, 94, 96, 96, 97, 99, 99, 99, 100, 100, 101, 103, 103, 103, 104, 105, 108, 109, 109, 109, 110, 111, 112, 113, 114, 114, 117, 119, 120, 120, 120, 122, 125, 125, 127, 128, 129]

我完全知道 ExecutorFork/join 的存在。但如前所述,我正在尝试使用线程来实现它。

如果递归的左分支和右分支都使用 (threadCount - 1) 个线程,那么它们将一起使用两倍的线程数:(2*threadCount - 2) 个线程。

你给每个分支的线程数应该加起来达到你给定的限制。例如,对于左右使用 50-50 的比例:

int threadsForBranches = threadCount - 1; // remove 1 to count current thread
tl = new Thread(new MergeSortRunner(left, threadsForBranches / 2));
tr = new Thread(new MergeSortRunner(right, threadsForBranches - threadsForBranches / 2));