gpt4 book ai didi

java - 并发元胞自动机 Actor 移动

转载 作者:行者123 更新时间:2023-12-01 09:05:12 26 4
gpt4 key购买 nike

我有一个二维元胞自动机。在某些细胞中可能存在一个行动者(代理)。每个 Actor 都是一个线程。我需要根据 Actor 单元周围的 9 个单元来移动 Actor 。我想同时执行此操作,以便单元格 (4,5) 中的参与者可以使用邻居单元格 (3,4)、(4,4)、(5,4)、(3,5)、(5,5) 、(3,6)、(4,6)、(5,6) 和其他参与者不能使用此单元格。如果某个 Actor 在他的附近有这些牢房,他必须等到第一个 Actor 搬走。但我想允许同时移动没有共同邻居的 Actor 。因此 (4,5) 中的角色可以与 (10,5) 中的角色同时移动,因为它们没有共同的邻居。

最好的解决方案是什么?你能提出一些建议吗?

最佳答案

大致的想法如下。

  1. 创建 Cell 对象矩阵,用于同步
  2. 将 Actor 分配给单元格
  3. 每当 Actor 移动到另一个单元格时,它都必须在该单元格上获得监视器

请注意,Actor 开始移动的单元格在下面的代码中不 protected 。另外,如果每个单元格都填充有一个 Actor,您会期望什么?

import java.util.ArrayList;
import java.util.List;

public class CellularAutomata {

public static void main(String ... args) throws InterruptedException {
final int rows = 5;
final int cols = 5;
Cell[][] matrix = new Cell[rows][cols];
List<Actor> actors = new ArrayList<>();
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
matrix[i][j] = new Cell();
//populate actors
if ((i + j) % 2 == 0) {
Actor actor = new Actor(matrix, i, j);
actor.setName(String.format("Actor %d %d", i, j));
actors.add(actor);
}
}
}
for (Actor actor : actors) {
actor.start();
}
for (Actor actor : actors) {
actor.join();
}
}

public static class Cell {}

public static class Actor extends Thread {

private final static int[][] circleMoves = {
{-1, -1}, {-1, 0}, {-1, 1}
, {0, 1}, {1, 1}, {1, 0}
, {1, -1}, {0, -1}, {0, 0}
};
private final Cell[][] matrix;
private final int row;
private final int col;

public Actor(Cell[][] matrix, int row, int col) {
this.matrix = matrix;
this.row = row;
this.col = col;
}

@Override
public void run() {
for (int i = 0; i < circleMoves.length; i++) {
int nextRow = row + circleMoves[i][0];
int nextCol = col + circleMoves[i][1];
if (nextRow >= 0 && nextRow < matrix.length
&& nextCol >= 0 && nextCol < matrix[nextRow].length) {
Cell targetCell = matrix[nextRow][nextCol];
System.out.println(Thread.currentThread().getName() + " waiting for cell (" + nextRow + ";" + nextCol + ")");
synchronized (targetCell) {
try {
System.out.println(Thread.currentThread().getName() + " moved to cell (" + nextRow + ";" + nextCol + ")");
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new IllegalStateException(e);
}
}
}
}
}

}

}

关于java - 并发元胞自动机 Actor 移动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41336590/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com