Android 异步处理程序 运行

Android handler running asynchronously

我有一个函数 gamePlay(),它看起来像这样:

 public void gamePlay()
{
    for (int i = 0; i < 4; i++)
    {
        currentRound = i;
        if (i == 0)
        {
            simulateTurns();
        }
        if(i == 1)
        {
            simulateTurns();
        }
        if (i > 1)
        {
           simulateTurns();
        }
    }
}

simulateTurns() 使用一个使用 Looper.getMainLooper() 参数实例化的处理程序,在调用 gamePlay() 之前如下所示:

thread = new Handler(Looper.getMainLooper());

simulateTurns():

public void simulateTurns()
{
    currentPlayer = players[playerIndex % numPlayers];

    if(currentPlayer.getPlayerID() == USER_ID) //user
    {
        if(!currentPlayer.hasFolded())
            showUserOptions(currentRound);
        else
        {
            playerIndex++;
            simulateTurns();
        }
    }
    else
    {
        hideUserOptions(0);

        // Give players the option to raise, call, fold, checking (dumb for now, needs AI and user input)
        // currentPlayer.getPlayerID() gets the current ID of the player
        int randAction = (int) (Math.random() * 4);
        String action = "";


        //DEBUG Simulate game
        Log.w("--------DEBUG--------", "Round: " + currentRound + " Bot: " + currentPlayer.getPlayerID() + " action: " + action + " pot: " + pot);

        thread.postDelayed(new Runnable(){
            public void run()
            {
                if(!betsEqual())
                    simulateTurns();
            }}, 5000);
    }
}

调试日志时,似乎所有轮次都是并行开始的,然后记录了第 3 轮的几轮。

如何让 for 循环 运行 与 simulateGame() 同步,以便 运行 轮次按顺序进行?

注意:我还在一些 onClickListeners 上调用了 simulateTurns()。

您的代码似乎令人困惑。如果你试图按顺序模拟转弯,你不应该使用异步函数,因为它旨在是异步的,而你并不是在寻求这种行为。

假设你正在尝试做异步事情因为你在等待事情发生(或者因为你不想阻塞 UI 线程),你必须在做之前做一些改变一切。

您正在使用全局变量进行回合计数。这意味着您的循环执行得非常快,启动所有内容,然后执行异步调用,因此,所有调用的变量都是 max (3)。

您应该有一个名为 "StartNextRound()" 的函数,它会在 "simulateTurn()" 的末尾调用。此函数应检查是否需要开始新一轮 (i<4),然后调用 simulateTurn() 的新实例。

总结一下:不要在需要之前启动异步任务。使用函数启动新一轮,并在上一轮结束时调用该函数。

这是处理异步最简单的方法。其他选项更复杂(并且可能内存效率不高)并且涉及线程之间的处理程序以便能够立即启动所有任务并让它们休眠直到正确的回合开始。保留一些不正确的东西(而且似乎有 "for test" 目的)是一项非常艰巨的工作。