问题描述
我猜@synchronized块不是对象相关的,而是线程相关的...对吗?在那种情况下,我们为什么要传递自我?
I guess @synchronized blocks are not object dependent but thread dependent...right? In that case why do we pass self?
推荐答案
@synchronized
是该语言提供的用于创建同步作用域的构造.由于使用简单的全局共享互斥锁并因此序列化应用程序中的每个@synchronized
作用域效率非常低,因此该语言允许我们指定同步点.
@synchronized
is a construct provided by the language to create synchronized scopes. As it would be highly inefficient to use a simple global shared mutex, and thus serializing every single @synchronized
scope in the application, the language allows us to specify a synchronization point.
然后由开发者决定哪些同步点适合该任务.
Then it's up to the developer(s) to decide which synchronization points are appropriate for the task.
在实例方法上,通常使用self:实例是同步点.可以在任意数量的实例上调用@synchronized(self)
范围,但对于给定的实例只能调用一次.每个@synchronized(self)
范围都将针对给定实例进行序列化.
On an instance method, using self is common: the instance is the synchronization point. The @synchronized(self)
scope can be called on any number of instances, but only once for a given instance. Every @synchronized(self)
scope will be serialized for a given instance.
当然,如果需要,您可以自由使用另一个同步点.您可以使用类(@synchronized(self.class)
)或其他任何适合您需要的东西.
Of course, you are free to use another synchronization point if you want to do so. You can use the class (@synchronized(self.class)
) or anything else that suits your needs.
这篇关于为什么我们在@synchronized块中传递self?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!