在 Java 7 中与结果并行,使用非最终变量

Parallel in Java 7 with a result, using non-final variables

我有一个类似的东西:

int [] array1 = new int[20];
int [] array2 = new int[20];
int total= 0;
Random generator = new Random();

for(int i = 0; i < 10000; i++){
    int tmp = generator.nextInt(20);
    boolean win = custom_function(...);
    array1[tmp]++;
    array2[tmp]++
    total++;
}

// do something with the arrays

而且我不知道如何并行实现!当使用

这样的结构时
ExecutorService exec =
    Executors.newFixedThreadPool(SOME_NUM_OF_THREADS);
try {
    for (final Object o : list) {
        exec.submit(new Runnable() {
            @Override
            public void run() {
                // do stuff with o.
            }
        });
    }
} finally {
    exec.shutdown();
}

我不能简单地 return 任何东西或改变任何东西,因为它只适用于最终变量!如何进行?


每个runnable 都应该修改变量array1[tmp]array2[tmp]array3[tmp]。请注意,这可以通过某种 fork join 来完成,我只是不知道该怎么做。

您似乎真的想要 Callable,它计算出一个结果,而不是 Runnable

submit(Callable) returns a Future 您可以调用 get 并检索结果。

import java.util.*;
import java.util.concurrent.*;

class Example {
    public static void main(String[] args) {
        final int n = 3;
        final int length = 20;

        ExecutorService ex = Executors.newFixedThreadPool(n);
        List<Future<int[]>> futures = new ArrayList<>();

        for (int i = 0; i < n; ++i) {
            futures.add(ex.submit(new Callable<int[]>() {
                Random r = new Random();

                @Override
                public int[] call() {
                    int[] result = new int[length];

                    for (int i = 0; i < length; ++i) {
                        int tmp = r.nextInt(length);
                        result[tmp]++;
                    }

                    return result;
                }
            }));
        }

        ex.shutdown();

        for (Future<int[]> f : futures) {
            try {
                System.out.println(Arrays.toString(f.get()));
            } catch (InterruptedException|ExecutionException e) {
                e.printStackTrace();
            }
        }
    }
}

示例输出:

[0, 1, 1, 1, 0, 1, 0, 2, 3, 1, 2, 0, 1, 2, 0, 2, 1, 2, 0, 0]
[2, 2, 1, 0, 0, 2, 1, 1, 3, 1, 2, 1, 0, 0, 1, 1, 0, 1, 1, 0]
[0, 1, 1, 1, 0, 1, 0, 4, 1, 2, 0, 1, 0, 1, 2, 2, 1, 0, 0, 2]