java从一个连续运行1000次到多线程的程序

时间:2013-12-11 20:28:00

标签: java multithreading

我仍然是java的新手,现在连续1000次运行此代码,所以它可能更有效率运行多线程,但我不知道最好的想法是将分数返回主线程< / p>

    private int StartGameRandom(EntityManager managerOrg, UserInput input)
{
    EntityManager manager = managerOrg.cloneState(managerOrg);
    int playerId = 0;
    int score = 0;

    //get the player id from the player that has to play
    ArrayList<Entity> tempState = manager.getAllWithComponents(PhaseComponent.class);
    if (tempState.isEmpty())
        System.err.println("ScoreSystem.addScorePlayer noPlayerComponent found");
    Entity state = tempState.get(0);
    PhaseComponent sComponent = (PhaseComponent) state.getComponent(PhaseComponent.class);
    playerId = sComponent.getPlayerId();

    SetPlayersToRandom(manager);
    new PhaseSystem(manager, input);

    ArrayList<Entity> tempPlayer = manager.getAllWithComponents(PlayerComponent.class);
    if (tempPlayer.isEmpty())
        System.err.println("montecarlo.startgamerandom noPlayerComponent found");
    Entity[] players = new Entity[tempPlayer.size()];
    tempPlayer.toArray(players);

    //set all the players to random ai
    for (Entity entity : players) {
        PlayerComponent component = (PlayerComponent) entity.getComponent(PlayerComponent.class);
        if (component.getPlayerID() == (byte)playerId)
        {
            score = component.getTotalScore();
            break;
        }
    }

    return score;
}

这就是我对分数的处理

                    for (int j = 0; j < RUNS; j++ )
                {
                    int score = StartGameRandom(manager,input);
                    maxScore = Math.max(score, maxScore);
                    if (j == 0)
                    {
                        minScore = score;
                        averageScore  = score;
                    }
                    else
                    {
                        minScore = Math.min(score, minScore);

                        averageScore  = ((averageScore*j)+score)/(j+1);
                    }
                }

那么在java中执行此操作的最佳方法是什么

1 个答案:

答案 0 :(得分:2)

制作多线程的东西并不会让事情变得更快。实际上,多线程不应该是您优化的第一选择。

我不完全确定你的代码是做什么的,但是由于它需要花费10分钟并且涉及EntityManager这一事实,我猜测数据库调用是罪魁祸首。

您应该调查每个部分花费多少时间,看看您的数据库查询是否效率低下,或者您是否进行了大量单独的调用(可以合并为更少的调用)。