类中的线程安全
请您看一下下面的代码并告诉我 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不,事实并非如此。
例如,两个线程可能无法通过
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, unlessPlayer.addScore
is thread-safe, score adding could be subtly wrong.Synchronizing over the whole
play
method (and reverting ofplayers
to a normal list) would solve these problems.