我写了以下片段:
static private int counter;
public void compute()
{
if (array.length<=500)
{
for(int i = 0;i<array.length;i++){
counter++;
System.out.println("Ciao this is a recursive action number"+ counter+Thread.currentThread().getName());
}
}
else{
int split = array.length/2;
RecursiveActionTry right = new RecursiveActionTry(split);
RecursiveActionTry left = new RecursiveActionTry(split);
invokeAll(right, left);
我看到 invokeAll()
自动派生了我传递给的两个 RecursiveActionTry
对象之一。我的笔记本电脑只有 2 个内核。如果我有 4 个内核并启动 4 个任务会怎么样...invokeAll(right, left, backward, forward);
我会使用所有 4 个内核吗?不知道,因为我只有 2 个内核。
我还想知道 invokeAll(right, left) 是否在幕后为第一个参数(右)调用 compute()
并为第一个参数调用 fork + join
第二个参数(左)。 (就像在 RecursiveTask 扩展中一样)。否则它不会使用并行性,对吗?
顺便说一句,如果有超过 2 个参数.. 它会在第一个参数上调用 compute()
并在所有其他参数上调用 fork 吗?
提前致谢。
最佳答案
invokeAll()
调用许多在不同线程上独立执行的任务。这并不需要为每个线程使用不同的核心,但它可以允许为每个线程使用不同的核心(如果可用)。细节由底层机器处理,但本质上(简单地)如果可用内核少于线程,它会对线程进行时间切片,以便允许一个内核在一个内核上执行一定时间,然后是另一个,然后是另一个(在循环中。)
And by the way, if there are more than 2 arguments.. does it call compute() on the first and fork on all the others?
它将compute()
所有的参数,然后compute()
方法负责委托(delegate)并在不满足worker阈值时 fork ,然后加入完成时的计算。 (尽管以两种以上的方式拆分它是不常见的 - fork join 通常通过每次递归将工作负载一分为二来工作,如果有必要的话。)
关于java - invokeAll 它究竟是如何工作的? ( fork 连接),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16896095/