我尽力在此Java代码中找到问题,但我找不到它-您能帮我吗?

我希望我提供的代码足够,但是如有必要,我会发布更多代码。

进一步致歉,我没有举一个最小的例子。

game.getGroupPlayers().list();
MoverThread[] playerThread = game.getPlayers();
System.out.println(playerThread.length);
for (int i = 0; i < playerThread.length; i++) {
    try {
        System.out.println(i + " -> " +playerThread[i].toString());
        returnString += playerThread[i].toString() + "\n";
    } catch(NullPointerException e) {
        System.out.println("Problem at i = " + i);
        e.printStackTrace();
    }
    game.getGroupPlayers().list();
}

有时会给我以下输出:



[编辑]
这是getPlayers()的来源
/*
 * post returns the games players as an array
 */
public MoverThread[] getPlayers() {
synchronized(movers) {
    MoverThread[] playerList = new MoverThread[players.activeCount()];
    players.enumerate(playerList);
    return playerList;
}
}

[编辑]
这是球员的产生方式
private ThreadGroup movers;
private ThreadGroup players;
private ThreadGroup ghosts;

private Observer observer;

/*
 * constructor
 */
 public Game(Maze maze, Referee referee) {
this.maze = maze;
this.referee = referee;
threadList = new ArrayList<MoverThread>();
movers = new ThreadGroup("Movers");
players = new ThreadGroup(movers, "Players");
ghosts = new ThreadGroup(movers, "Ghosts");
observer = null;
}

[编辑]

这是我如何调用产生问题的方法:
/*
 * post checks if the players thread was interrupted - if not if hostfield pretends to be a goal the game gets stopped and referee is called to perform "goal-found-actions"
 */
private void checkGoal() {
if (!getThread().isInterrupted()) {
    synchronized(getGame().getMovers()) {
        if (!getThread().isInterrupted()) {
            if (getHostField().isGoal()) {
                Field goal = getHostField();
                getGame().getReferee().goalFound(this, goal);
                getGame().setGameOver();
            }
        }
    }
}
}

这是整个目标的Found()
/*
 * post action to be performed if a player finds a goal
 * print some information
*/
public void goalFound(Player player, Field at) {
//FIXME get the Bug!!!
String returnString = "Game over - player " + player.getName() + " found a goal on (" + at.getPos()[0] + ", "  + at.getPos()[1] + ")!\n";
game.getGroupPlayers().list();
MoverThread[] playerThread = game.getPlayers();
System.out.println(playerThread.length);
for (int i = 0; i < playerThread.length; i++) {
    try {
        System.out.println(i + " -> " +playerThread[i].toString());
        returnString += playerThread[i].toString() + "\n";
    } catch(NullPointerException e) {
        System.out.println("Problem at i = " + i);
        e.printStackTrace();
    }
}
game.getGroupPlayers().list();
returnString += game.mazeString();
System.out.println(returnString);
}

最佳答案

没有一种枚举ThreadThreadGroup的好方法。这是一个众所周知的可怕设计。

在调用ThreadGroup.activeCountThreadGroup.enumerate(Thread[])之间,线程可能已经启动或死亡。最好的办法是在分配数组时在activeCount中添加一个软糖因子。如果返回的值与数组长度匹配,则您可能错过了一些值,应该以更大的数组大小(可能是一个更大的因数,而不只是添加一个常数)重复进行。成功后,您将需要适本地修剪数组(或将其照这样处理)。

10-01 10:57