rankedPlayersWaitingForMatch

rankedPlayersWaitingForMatch

我在这里有此代码块,我需要确保rankedPlayersWaitingForMatch在线程之间正确同步。我本打算使用synchronize,但是由于if语句中使用了变量,所以我认为在这里不起作用。我在线阅读了有关final Lock lock = new ReentrantLock();的内容,但对于在这种情况下如何与try/finally块一起正确使用它,我有些困惑。我可以举个简单的例子吗?谢谢

// start synchronization
if (rankedPlayersWaitingForMatch.get(rankedType).size() >= 2) {
  Player player1 = rankedPlayersWaitingForMatch.get(rankedType).remove();
  Player player2 = rankedPlayersWaitingForMatch.get(rankedType).remove();
  // end synchronization
  // ... I don't want this all to be synchronized, just after the first 2 remove()
} else {
  // end synchronization
  // ...
}

最佳答案

这是您想做的:

boolean has_players = false;
Player player1;
Player player2;
synchronize (rankedPlayersWaitingForMatch) {
  if (rankedPlayersWaitingForMatch.get(rankedType).size() >= 2) {
    player1 = rankedPlayersWaitingForMatch.get(rankedType).remove();
    player2 = rankedPlayersWaitingForMatch.get(rankedType).remove();
    has_players = true;
  }
}

if(has_players){
  // ... I don't want this all to be synchronized, just after the first 2 remove()
}
else{
  // ...
}

07-25 20:29