【问题标题】:Designing a multi-thread matrix in Java用Java设计一个多线程矩阵
【发布时间】:2015-06-17 13:30:08
【问题描述】:

我有一个矩阵来实现 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() 方法可以理解,是让每个单元(线程)运行并等待由LifeMatrix 类中的变量currentAction 表示的正确操作状态,然后继续执行所需的操作。

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

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

【问题讨论】:

  • 如果目标是学习如何管理线程,这是一个很好的练习。如果目标是制作一个好的工作应用程序,那么最好使用单个线程来更新单元格。
  • 这确实是一个大学练习线程同步的练习......任何粗略的方向也很好......如何让所有线程等到 LifeMatrix 对象中的变量 currentAction 发生变化?

标签: java multithreading


【解决方案1】:

使用CyclicBarrier 应该很容易理解:

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

伪代码:

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;
             }
        }
    }
}

【讨论】:

  • 这将使单元格连续运行,并且不会暂停让用户启动下一个循环
  • 很好:P 我写这篇文章的时候忘记了。但是可以通过更改为CyclicBarrier barrier = new CyclicBarrier(noOfCells + 1); 轻松完成,并且当用户启动每个循环时,执行barrier.await(); barrier.await(); (或者如果OP需要,可以拆分为2个屏障,这使得在这方面更清楚)
  • 是的,这就是我在回答中使用两个 Phasers 的原因 - 我不喜欢双重呼叫 await()。在这种情况下它可以正常工作,但如果单元格执行更高级的操作需要更长的时间,则主线程在等待单元格时被锁定 - 在现实世界的应用程序中,这意味着 UI 将被冻结。
  • 是的,我可以更新我的答案以使用 2 个障碍 :) 这应该可以解决问题
【解决方案2】:

我会使用两个Phasers 来解决这个问题。

您使用一个Phaser 来控制周期,一个用于在确定细胞是否存活时同步细胞。

public class Cell extends Thread {
    private LifeMatrix ownerLifeMat; // the matrix owner of the cell
    private boolean alive;
    private int xCoordinate, yCoordinate;

    // Phaser that controls the cycles
    private Phaser cyclePhaser;

    // Phaser for cell synchronisation
    private Phaser cellPhaser;

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

        // Register with the phasers
        this.cyclePhaser.register();
        this.cellPhaser.register();
    }

    public void run() {
        boolean newAlive;

        while (true) {
            // Await the next cycle
            cyclePhaser.arriveAndAwaitAdvance();

            // now check neighbors
            newAlive = decideNewLifeState();

            // Wait until all cells have checked their state
            cellPhaser.arriveAndAwaitAdvance();

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

    // Other methods redacted
}

您可以通过在cyclePhaser 上注册主线程来控制周期 并让它arrive 开始下一个周期。

【讨论】:

  • 只是好奇,似乎在这种情况下使用屏障会更简单(实际上我们只需要一个移相器/屏障),有什么理由在您的解决方案中选择移相器(和 2 个移相器)?
  • 使用2的原因是主线程需要在进入下一个周期时到达,但在cell检查状态时没有业务这样做。使用Phaser 而不是CyclicBarrier 的原因是因为我更喜欢它(静态参与者数量vs (de)register),并且它具有不等待其他线程的arrive 方法。 Phaser 更加通用,我认为 CyclicBarrier 已经过时了。
猜你喜欢
  • 2018-07-12
  • 2017-05-04
  • 1970-01-01
  • 2014-12-16
  • 2018-02-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多