异步运行的Android处理程序
我有一个功能,gamePlay,看起来像这样:异步运行的Android处理程序,android,multithreading,synchronous,handlers,Android,Multithreading,Synchronous,Handlers,我有一个功能,gamePlay,看起来像这样: public void gamePlay() { for (int i = 0; i < 4; i++) { currentRound = i; if (i == 0) { simulateTurns(); } if(i == 1) { simulateTurns();
public void gamePlay()
{
for (int i = 0; i < 4; i++)
{
currentRound = i;
if (i == 0)
{
simulateTurns();
}
if(i == 1)
{
simulateTurns();
}
if (i > 1)
{
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同步运行,从而使循环按顺序运行
注意:我还在一些onClickListener上调用simulateTurns 您的代码似乎令人困惑。如果您试图按顺序模拟转弯,则不应使用异步函数,因为它旨在实现异步,而您并不是在寻求该行为 假设您正在尝试执行异步操作,因为您正在等待事情发生,或者因为您不想阻止UI线程,那么您必须在执行所有操作之前进行一些更改 您正在使用全局变量进行舍入计数。这意味着您的循环执行得非常快,启动了所有东西,然后执行异步调用,因此,变量max为3 for all call
您应该有一个名为StartNextRound的函数,它在simulateTurn的末尾被调用。这个函数应该检查,而它是需要开始新一轮的第二发现你的代码相当混乱。也许你应该考虑重新设计它是一个烂摊子,但线程。推迟后可能是你的问题。你想要的是每次停止/暂停/睡眠5秒钟,对吗?如果是这样,请更改此代码,处理程序将不会像这样工作。您的第二个建议帮助我使程序正常工作。非常感谢你!那么你能接受这个答案吗,或者向其他读者解释一下你做了什么?我和你做的完全一样,在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);
}
}