类中的线程安全

发布于 2024-11-18 15:52:35 字数 482 浏览 1 评论 0原文

请您看一下下面的代码并告诉我 ClassA 是否是线程安全的?如果它不是线程安全的,你能告诉我它在哪里中断吗?

public class ClassA {

private List<Player> players;

public ClassA() {
this.players = Collections.synchronizedList(new ArrayList<Player>());
}

public Player play(Player player){
int score = 0;
.
.
.

if (players.contains(player)) {
player = players.get(players.indexOf(player));
player.addScore(score);
} else {
player.addScore(score);
players.add(player);
}
return player;

}

}

Please can you have a look at the following code and advise whether ClassA is thread-safe or not? If it is not thread-safe, could you please advise where it is breaking?

public class ClassA {

private List<Player> players;

public ClassA() {
this.players = Collections.synchronizedList(new ArrayList<Player>());
}

public Player play(Player player){
int score = 0;
.
.
.

if (players.contains(player)) {
player = players.get(players.indexOf(player));
player.addScore(score);
} else {
player.addScore(score);
players.add(player);
}
return player;

}

}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

没有心的人 2024-11-25 15:52:35

不,事实并非如此。

例如,两个线程可能无法通过 players.contains 测试,并且都添加自己的播放器版本(更好的方法是每次都将播放器添加到集合中)。另外,除非 Player.addScore 是线程安全的,否则分数添加可能会出现微妙的错误。

同步整个 play 方法(并将 players 恢复到正常列表)可以解决这些问题。

No, it is not.

For example, two threads could fail the players.contains test and both add their version of a player (a better way would just add the player every time to a set). Also, unless Player.addScore is thread-safe, score adding could be subtly wrong.

Synchronizing over the whole play method (and reverting of players to a normal list) would solve these problems.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文