在阵列上同步.它是在所有元素上还是在数组对象上同步? [英] Synchronizing on an array. Does it synchronize on all the elements or on the array object?

查看:30
本文介绍了在阵列上同步.它是在所有元素上还是在数组对象上同步?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我在一个数组上同步,这是否意味着我正在同步其中的所有元素,还是我正在同步数组对象?如果后者为真,那么我如何一次同步数组中的所有元素,以确保在执行某个块时会访问 non ?

If I synchronize on an array, does this mean that I'm synchronizing on all the elements in it or am I synchronizing on the array object? If the latter is true, then how can I synchronize on all the elements in an array at once so that I can make sure non will be accessed while executing a certain block?

例如假设我们有一个银行账户数组,我们希望确保在执行某个代码块时没有线程可以访问任何账户.

E.g. Lets say we have an array of bank accounts and we want to make sure no thread can access any account when a certain block of code is being executed.

推荐答案

它在监视器上为数组本身同步.

It synchronizes on the monitor for the array itself.

即使您可以同步所有元素,也不能确保它们不被访问 - 因为同步只是建议性的.

Even if you could synchronize on all the elements, that wouldn't ensure that they weren't accessed - because synchronization is only advisory.

这里的解决办法大概是封装:根本不允许其他代码看到数组本身.这样你就可以控制其他代码如何通过你自己的方法访问数组的成员(例如 ArrayList 就是这样做的).

The solution here is probably encapsulation: don't allow other code to see the array itself at all. That way you can control how other code is able to access the members of the array, via your own methods (like ArrayList does, for example).

请注意,即使您执行了所有这些操作,它也不会阻止其他代码在您的独占代码开始运行之前获取数组元素,然后在您的独占代码运行时使用该引用(例如改变它所指的对象).您并未真正向我们提供有关您尝试执行的操作的太多信息,但您可能需要采取不同的方法.

Note that even if you do all of this, it won't stop other code from fetching the array element before your exclusive code starts running, and then using that reference while your exclusive code is running (e.g. mutating the object it refers to). You haven't really given us much information about what you're trying to do, but you may need to take a different approach.

这篇关于在阵列上同步.它是在所有元素上还是在数组对象上同步?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆