i want this code in Java 1.8 to run parallel on more processors:
// 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;
}
}
It's part of the code from the game of life implementation. How can i make it parallel so the function one_cell_generation
will run multiple times on more processors (perhaps threads?). I am new in Java. Thanks. Here is my whole code of the Game of Life implementation:
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;
}
}
}