Java:除了它们所属的对象之外,什么东西被同步方法锁住了? [英] Java: What, if anything, is locked by synchronized methods apart from the object they belong to?

查看:206
本文介绍了Java:除了它们所属的对象之外,什么东西被同步方法锁住了?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在,我不确定这是否是一个愚蠢的问题,请耐心等待。

Now, I'm not sure whether this is a stupid question, please bear with me if it is.

是一个对象的递归一世。 e。如果两个对象在它们的字段中引用了第三个对象,并且线程正在两个对象中的一个上运行同步方法,那么任何其他线程可以访问第三个对象吗?

Is the lock on an object "recursive", i. e. if two objects have references to a third object in their fields and a thread is running a synchronized method on one of the two, can any other thread access the third object?

// a and b are some objects that implement Runnable
// they both reference the same third object
a.ref = c;
b.ref = c;

// a is run in a thread and processes some data in a loop for a long time
// the method the loop belongs to is declared synchronized
threadA = new Thread(a);
threadA.start();

a.someSyncedMethod(); // this would block ...
b.ref.someOtherSyncedMethod(); // ... but would this?
a.ref.someOtherSyncedMethod(); // ... and how about this?


推荐答案

和锁定对象。没有真正的想法锁定对象 - 有获取(和释放)与对象相关的锁。是的,它听起来像我nitpicking - 但区别是重要的,因为如果你谈论一个被锁定,它听起来像没有其他线程将能够改变对象中的任何东西,而锁是

It's worth separating out the concepts of "a lock" and "locking an object". There's no real idea of "locking an object" - there's "acquiring (and releasing)" the lock associated with an object. Yes, it sounds like I'm nitpicking - but the distinction is important because if you talk about an object being locked it sounds like no other threads will be able to change anything in the object while that lock is held.

相反,它只是意味着没有其他线程将能够获取相同的锁,而持有锁。

Instead, it just means that no other thread will be able to acquire the same lock while the lock is held. There's no direct relationship between the lock and any of the contents of the object that the lock is associated with.

声明为synchronized的方法获取与该实例关联的锁,他们所属的对象。这只会使同一对象上的其他同步方法等待,并且同步语句明确同步它。

Methods declared "synchronized" acquire the lock associated with the instance of the object they belong to. This only makes other synchronized methods on the same object wait, and synchronized statements that explicitly sync on it.

我个人不喜欢同步方法 - 我喜欢通过在仅用于同步的(私有,最终)成员变量上显式同步来清除。

Personally I don't like synchronized methods - I like to make it clearer by explicitly synchronizing on a (private, final) member variable which is only used for synchronization.

这篇关于Java:除了它们所属的对象之外,什么东西被同步方法锁住了?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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