java - 用Java设计多线程矩阵

标签 java multithreading

我有一个实现 John Conway 生命模拟器的矩阵,其中每个单元格代表生命或缺乏生命。

每个生命周期都遵循以下规则:

  1. 任何少于两个活邻居的活细胞都会死亡,好像是由人口不足引起的。

  2. 任何有两个或三个活邻居的活细胞都会存活到下一代。

  3. 任何有超过三个活邻居的活细胞都会死亡,就像过度拥挤一样。

  4. 任何死细胞只要有三个活的邻居就会变成活细胞,就像通过繁殖一样。

每个单元格都有一个线程,它将按照上面列出的规则执行更改。

我已经实现了这些类:

import java.util.Random;

public class LifeMatrix {
    Cell[][] mat;
    public Action currentAction = Action.WAIT_FOR_COMMAND;
    public Action changeAction;

    public enum Action {
        CHECK_NEIGHBORS_STATE,
        CHANGE_LIFE_STATE,
        WAIT_FOR_COMMAND
    }

    // creates a life matrix with all cells alive or dead or random between dead or alive
    public LifeMatrix(int length, int width) {
        mat = new Cell[length][width];

        for (int i = 0; i < length; i++) { // populate the matrix with cells randomly alive or dead
            for (int j = 0; j < width; j++) {
                mat[i][j] = new Cell(this, i, j, (new Random()).nextBoolean());
                mat[i][j].start();
            }

        }
    }

    public boolean isValidMatrixAddress(int x, int y) {
        return x >= 0 && x < mat.length && y >= 0 && y < mat[x].length;
    }

    public int getAliveNeighborsOf(int x, int y) {
        return mat[x][y].getAliveNeighbors();
    }

    public String toString() {
        String res = "";
        for (int i = 0; i < mat.length; i++) { // populate the matrix with cells randomly alive or
                                               // dead
            for (int j = 0; j < mat[i].length; j++) {
                res += (mat[i][j].getAlive() ? "+" : "-") + "  ";
            }
            res += "\n";
        }
        return res;
    }


    public void changeAction(Action a) {
        // TODO Auto-generated method stub
        currentAction=a;
        notifyAll();                 //NOTIFY WHO??
    }
}

/**
 * Class Cell represents one cell in a life matrix
 */
public class Cell extends Thread {
    private LifeMatrix ownerLifeMat; // the matrix owner of the cell
    private boolean alive;
    private int xCoordinate, yCoordinate;

    public void run() {
        boolean newAlive;

        while (true) {
            while (! (ownerLifeMat.currentAction==Action.CHECK_NEIGHBORS_STATE)){
                synchronized (this) {//TODO to check if correct


                try {
                    wait();
                } catch (InterruptedException e) {
                    System.out.println("Interrupted while waiting to check neighbors");
                }}
            }
            // now check neighbors
            newAlive = decideNewLifeState();

            // wait for all threads to finish checking their neighbors
            while (! (ownerLifeMat.currentAction == Action.CHANGE_LIFE_STATE)) {
                try {
                    wait();
                } catch (InterruptedException e) {
                    System.out.println("Interrupted while waiting to change life state");
                };
            }

            // all threads finished checking neighbors now change life state
            alive = newAlive;
        }
    }

    // checking the state of neighbors and
    // returns true if next life state will be alive
    // returns false if next life state will be dead
    private boolean decideNewLifeState() {
        if (alive == false && getAliveNeighbors() == 3)
            return true; // birth
        else if (alive
                && (getAliveNeighbors() == 0 || getAliveNeighbors() == 1)
                || getAliveNeighbors() >= 4)
            return false; // death
        else
            return alive; // same state remains

    }

    public Cell(LifeMatrix matLifeOwner, int xCoordinate, int yCoordinate, boolean alive) {
        this.ownerLifeMat = matLifeOwner;
        this.xCoordinate = xCoordinate;
        this.yCoordinate = yCoordinate;
        this.alive = alive;
    }

    // copy constructor
    public Cell(Cell c, LifeMatrix matOwner) {
        this.ownerLifeMat = matOwner;
        this.xCoordinate = c.xCoordinate;
        this.yCoordinate = c.yCoordinate;
        this.alive = c.alive;
    }

    public boolean getAlive() {
        return alive;
    }

    public void setAlive(boolean alive) {
        this.alive = alive;
    }

    public int getAliveNeighbors() { // returns number of alive neighbors the cell has
        int res = 0;
        if (ownerLifeMat.isValidMatrixAddress(xCoordinate - 1, yCoordinate - 1) && ownerLifeMat.mat[xCoordinate - 1][yCoordinate - 1].alive)
            res++;
        if (ownerLifeMat.isValidMatrixAddress(xCoordinate - 1, yCoordinate) && ownerLifeMat.mat[xCoordinate - 1][yCoordinate].alive)
            res++;
        if (ownerLifeMat.isValidMatrixAddress(xCoordinate - 1, yCoordinate + 1) && ownerLifeMat.mat[xCoordinate - 1][yCoordinate + 1].alive)
            res++;
        if (ownerLifeMat.isValidMatrixAddress(xCoordinate, yCoordinate - 1) && ownerLifeMat.mat[xCoordinate][yCoordinate - 1].alive)
            res++;
        if (ownerLifeMat.isValidMatrixAddress(xCoordinate, yCoordinate + 1) && ownerLifeMat.mat[xCoordinate][yCoordinate + 1].alive)
            res++;
        if (ownerLifeMat.isValidMatrixAddress(xCoordinate + 1, yCoordinate - 1) && ownerLifeMat.mat[xCoordinate + 1][yCoordinate - 1].alive)
            res++;
        if (ownerLifeMat.isValidMatrixAddress(xCoordinate + 1, yCoordinate) && ownerLifeMat.mat[xCoordinate + 1][yCoordinate].alive)
            res++;
        if (ownerLifeMat.isValidMatrixAddress(xCoordinate + 1, yCoordinate + 1) && ownerLifeMat.mat[xCoordinate + 1][yCoordinate + 1].alive)
            res++;
        return res;
    }

}

public class LifeGameLaunch {

    public static void main(String[] args) {
        LifeMatrix lifeMat;
        int width, length, populate, usersResponse;
        boolean userWantsNewGame = true;
        while (userWantsNewGame) {
            userWantsNewGame = false; // in order to finish the program if user presses
                                      // "No" and not "Cancel"
            width = Integer.parseInt(JOptionPane.showInputDialog(
                    "Welcome to John Conway's life simulator! \n"
                            + "Please enter WIDTH of the matrix:"));
            length = Integer.parseInt(JOptionPane.showInputDialog(
                    "Welcome to John Conway's life simulator! \n"
                            + "Please enter LENGTH of the matrix:"));


            lifeMat = new LifeMatrix(length, width);

            usersResponse = JOptionPane.showConfirmDialog(null, lifeMat + "\nNext cycle?");
            while (usersResponse == JOptionPane.YES_OPTION) {
                if (usersResponse == JOptionPane.YES_OPTION) {
                    lifeMat.changeAction(Action.CHECK_NEIGHBORS_STATE);
                } 
                else if (usersResponse == JOptionPane.NO_OPTION) {
                    return;
                }
                // TODO leave only yes and cancel options
                usersResponse = JOptionPane.showConfirmDialog(null, lifeMat + "\nNext cycle?");
            }
            if (usersResponse == JOptionPane.CANCEL_OPTION) {
                userWantsNewGame = true;
            }
        }
    }
}

我的麻烦是同步线程: 只有在所有线程都检查了它们的邻居之后,每个单元(一个线程)才必须改变它的生命/死亡状态。用户将通过单击按钮调用每个下一个生命周期。

我的逻辑,从run()方法可以理解是让每个cell(thread)运行并等待由变量currentAction<表示的正确 Action 状态LifeMatrix 类中,然后继续执行所需的操作。

我遇到的问题是如何将这些消息传递给线程以了解何时等待以及何时执行下一个操作?

任何改变程序设计的建议都非常受欢迎,只要每个单元格都用单独的线程实现!

最佳答案

使用 CyclicBarrier应该很容易理解:

(更新为使用 2 个屏障,并利用内部类使单元格看起来更短更干净)

伪代码:

public class LifeMatrix {
    private CyclicBarrier cycleBarrier;
    private CyclicBarrier cellUpdateBarrier;
    //.....

    public LifeMatrix(int length, int width) {
        cycleBarrier = new CyclicBarrier(length * width + 1);
        cellUpdateBarrier = new CyclicBarrier(length * width);

        // follow logic of old constructor
    }

    public void changeAction(Action a) {
        //....
        cycleBarrier.await()
    }

    // inner class for cell
    public class Cell implements Runnable {
        // ....

        @Override
        public void run() {
             while (...) {
                 cycleBarrier.await();  // wait until start of cycle
                 boolean isAlive = decideNewLifeState();
                 cellUpdateBarrier.await();  // wait until everyone completed
                 this.alive = isAlive;
             }
        }
    }
}

关于java - 用Java设计多线程矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30893111/

相关文章:

Java - 如何从文本文件中删除空行

java - 加入 Java 中的任意线程之一

python - 使用多 GPU 和多线程、Pytorch 进行对象检测推理

java - Java TCP 聊天客户端中的多线程/IO 流问题

multithreading - 使用 Qt 增强 asio

java - Android AlarmManager设置?

java - 关闭和回调

java - 将带有数据的 Java 代码打包到 .jar 中

JavaFX : updating progress for the multiple tasks

java - 如何使用 Ant 和 Ivy 构建项目及其依赖项