使用私有变量来锁定同步块
您好,我正在研究线程并用它们实现一些简单的示例。另外,我知道如何锁定和使用同步语句,但我看到了这样的例子;
private List<Foo> myList = new ArrayList<Foo>();
private Map<String,Bar) myMap = new HashMap<String,Bar>();
public void put( String s, Bar b ) {
synchronized( myMap ) {
myMap.put( s,b );
// then some thing that may take a while like a database access or RPC or notifying listeners
}
}
那么变量如何以及为什么可以用作同步块的锁呢?我总是使用“这个”词来访问该声明。
hi there i am working on threads and implement some simple examples with them. In addition, i know how to lock and use a synchronized statement but i saw an example like this;
private List<Foo> myList = new ArrayList<Foo>();
private Map<String,Bar) myMap = new HashMap<String,Bar>();
public void put( String s, Bar b ) {
synchronized( myMap ) {
myMap.put( s,b );
// then some thing that may take a while like a database access or RPC or notifying listeners
}
}
so how and why can be a variable used as a lock of a synchronized block_?. i always using "this" word for accessing to the statement.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用任何不具有弱标识的引用类型来锁定代码块。通常的做法是使用
this
指针。但是是否应该使用成员变量取决于类的行为。例如,如果您有四个方法,其中两个使用
var1
,另外两个使用var2
。现在,如果您只想根据这些变量来同步这些方法,那么您可以选择使用变量来锁定,而不是this
。You can use any reference type that does not have a weak identity to lock a block of code. It is a general practice to use the
this
pointer. But whether you should use a member variable depends on the behavior of your class.For instance if you have four methods out of which two use
var1
and the other two usevar2
. Now if you want to synchronize these methods only based on these variables then you could choose to use the variables to lock instead ofthis
.在 Java 中,每个对象实例都有一个与其关联的锁。
您需要对象的引用才能执行同步块语句。
没有必要对同步块使用相同的对象。您对此完全没问题:
但现在的技巧是确保每次访问 myMap 对象时都使用相同的对象。
因此,最好使用与您操作的对象相同的对象来充当锁。
当您想要执行一个小的同步块并且不费心为其创建新对象时,可以使用此方法。这将非常适合这种情况。
我希望这可以帮助您理解java的同步方法。
问候,
蒂贝留
In Java, each object instance has a lock associated with it.
You need a object's reference in order to do a synchronized block statement.
It's not necessary to use the same object for a synchronized block. You would be perfectly fine with this:
But the trick now, is to make sure you use the same object whenever you access myMap object.
So it's a good practice to use the same object that you operation on, to act as a lock..
This is used when you want to do a small synchronized block and don't bother creating a new object for it.. this will work fine for that.
I hope that helped you understand java's synchronization approach.
Regards,
Tiberiu
这是一个指向当前对象的指针,但 myMap 也是一个对象,是实现 Serialized 接口的 HashMap 类的实例
this is a pointer to the current object, but myMap is also an object, an instance of the class HashMap which implements the Serializable interface