使用同步列表

发布于 2024-09-13 07:27:08 字数 620 浏览 2 评论 0原文

这是我第一次使用 synchronized 关键字,所以我仍然不确定它到底是如何工作的。我有一个列表,我想由多个线程访问,所以我这样做:

players = Collections.synchronizedList(new ArrayList<Player>(maxPlayers));

现在,我想确保我没有在调用 players.add() 的同时调用 Players.get(),所以我认为我应该使用同步语句(方法A和B可以同时调用):

public void A() {
    synchronized(players) {
        players.add(new Player());
    }
}

public void B(String msg) {
    synchronized(players) {
        for(int i = 0;i<players.size();i++) {
            players.get(i).out.println(msg);
        }
    }
}

这是正确的过程吗?如果不是,我该怎么办?

This is my first time using the synchronized keyword, so I am still unsure of how it exactly works. I have a list that I want to be accessed by multiple threads so I do this:

players = Collections.synchronizedList(new ArrayList<Player>(maxPlayers));

Now, I want to make sure that I am not calling players.add() at the same time as players.get(), so I think i should use synchronized statements (methods A and B could be called at the same time):

public void A() {
    synchronized(players) {
        players.add(new Player());
    }
}

public void B(String msg) {
    synchronized(players) {
        for(int i = 0;i<players.size();i++) {
            players.get(i).out.println(msg);
        }
    }
}

Is this the correct procedure? If not, what should I do instead?

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

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

发布评论

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

评论(1

旧人九事 2024-09-20 07:27:08

如果您仅通过synchronizedList返回的对象访问列表,那么访问应该是线程安全的,但请注意,您可能需要使用同步块来执行复合操作,例如迭代列表或基于对列表的多次调用来制定操作和决策(例如,获取一个值做出决定然后添加一个值)。

因此,在您的示例中,A() 不需要同步块,但如果您不希望列表在迭代期间被更改或被其他线程读取,则 B() 可能需要。 (事实上​​,通过使用计数器来迭代它需要防止循环终止条件和另一个线程删除项目之间的竞争条件;但其他迭代方式可能不会有这个问题)。

Provided you only access the list through the object returned by synchronizedList then access should be thread-safe, though note that you may need to used synchronized blocks for compound actions like iterating through the list or making actions and decisions based on multiple calls into the list (for example, getting a value making a decision then adding a value).

So in your example A() doesn't need the synchronized block, but B() might if you don't want the list to be changed or be read by some other thread during the iteration. (In fact, by using the counter to iterate it is needed to prevent a race condition between the loop termination condition and another thread removing an item; other ways of iterating might not have this issue though).

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