带参数传递的 Java 并行 for 循环

标签 java multithreading multiprocessing

我希望 Java 1.8 中的这段代码能够在更多处理器上并行运行:

        // Make iterations
        for(int i = 0; i < numberOfIterations; i++) {
            for(int m = 0; m < gridsize; m++) {
                for(int n = 0; n < gridsize; n++) {
                    one_cell_generation(grid, grid2, m, n);
                }
                int n = 0;
            }

        }

这是生命游戏实现的代码的一部分。我怎样才能使其并行,以便函数 one_cell_ Generation 将在更多处理器(也许是线程?)上运行多次。我是 Java 新手。谢谢。这是我的生命游戏实现的完整代码:

package gameoflife;

public class GameOfLife {

    public static int gridsize = 5;
    public static int numberOfIterations = 100;
    public static String liveCell = "x";
    public static String deadCell = "o";

    public static void main(String[] args) {
        // Probability that cell is live in random order
        double p = 0.1;

        Boolean[][] grid = new Boolean[gridsize][gridsize];
        Boolean[][] grid2 = new Boolean[gridsize][gridsize];


        // Set up grid
        for(int m = 0; m < gridsize; m++) {
            for(int n = 0; n < gridsize; n++) {
                grid[m][n] = false;
                if(Math.random() < p) {
                    grid[m][n] = true;
                }
                // Copy grid
                grid2[m][n] = grid[m][n];
            }
        }

        // Make iterations
        for(int i = 0; i < numberOfIterations; i++) {
            for(int m = 0; m < gridsize; m++) {
                for(int n = 0; n < gridsize; n++) {
                    one_cell_generation(grid, grid2, m, n);
                }
                int n = 0;
            }

        }

        print_grid(grid);


    }

    public static void print_grid(Boolean[][] grid) {
        for(int m = 0; m < gridsize; m++) {
            for(int n = 0; n < gridsize; n++) {
                if(grid[m][n] == false) {
                    System.out.print(deadCell);
                } else {
                    System.out.print(liveCell);
                }

            }
            System.out.println();
        }
    }

    public static void one_cell_generation(Boolean[][] oldGrid, Boolean[][] newGrid, int m, int n) {
        // count live and dead neighbors
        int liveNeighbours = 0;
        // iterate over neighbors
        // check borders
        if(m > 0) {
            if(oldGrid[m-1][n] == true) {
                liveNeighbours += 1;
            }
            if (n > 0) {
                if(oldGrid[m-1][n-1] == true) {
                    liveNeighbours += 1;
                }
            }
            if(n < (gridsize - 1)) {
                if (oldGrid[m-1][n+1] == true) {
                    liveNeighbours += 1;
                }
            }
        }
        if (m < (gridsize - 1)) {
            if (oldGrid[m+1][n] == true) {
                liveNeighbours += 1;
            }

            if(n > 0) {
                if(oldGrid[m+1][n-1] == true) {
                    liveNeighbours += 1;
                }
            }
            if(n < (gridsize - 1)) {
                if(oldGrid[m+1][n+1] == true) {
                    liveNeighbours += 1;
                }
            }
        }

        if (n > 0) {
            if (oldGrid[m][n-1] == true) {
                liveNeighbours += 1;
            }
        }
        if(n < (gridsize - 1)) {
            if(oldGrid[m][n+1] == true) {
                liveNeighbours += 1;    
            }
        }

        // conway's game of life rules
        // apply rules to new grid
        if(liveNeighbours < 2 || liveNeighbours > 3) {
            newGrid[m][n] = false;
        }
        if(liveNeighbours == 3) {
            newGrid[m][n] = true;
        }
    }

}

最佳答案

外层循环是在不同代之间循环的时间序列,因此不能并行化而不影响最终结果。

两个内循环根据上一代的状态计算当前一代的状态,并且可以轻松并行化。

这是一种使用 parallel 的方法IntStream :

static int numberOfIterations = 100;
static int gridSize = 5;

public static void main(String[] args) {
    Boolean[][] grid1 = new Boolean[gridSize][gridSize];
    Boolean[][] grid2 = new Boolean[gridSize][gridSize];

    // initialize grids here

    for(int i = 0; i < numberOfIterations; i++) {
        // parallel processing
        IntStream.range(0, gridSize * gridSize).parallel().forEach(mn -> {
            int m = mn / gridSize;
            int n = mn % gridSize;

            oneCellGeneration(grid1, grid2, m, n);
        });

        // copy new grid to old grid here
    }
}

public static void oneCellGeneration(Boolean[][] grid1, Boolean[][] grid2,
        int m, int n) {
    // your cell generation logic here
}
<小时/>

注释 1:我重命名了一些方法和变量以符合 Java 命名约定。
注2:您忘记在原始代码中完成(或开始)生成后将新网格复制到旧网格。

关于带参数传递的 Java 并行 for 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59476807/

相关文章:

python - 在Python3中Pickle一个GdkPixbuf.Pixbuf对象

python-3.x - Python 多进程调度

multithreading - QT:从其他线程运行独立线程

android - Android 应用程序中的线程

python - 当 QThread 有事件队列时,用 exit() 终止线程是否安全?

java - 将 JSON 发送到 Spring MVC Controller

python - 将串行任务转换为并行以映射输入和输出

java - 如何在接受 `Derived` 的重写方法中使用类型 `Base` 的参数?

java - java中libtensorflow_framework.so.1无法打开错误是什么意思

java - Android 应用程序创建不在 Activity 中的内部文件