使用synchronized(lock)时,锁对象最好是静态的还是非静态的?

编程入门 行业动态 更新时间:2024-10-16 02:26:28
本文介绍了使用synchronized(lock)时,锁对象最好是静态的还是非静态的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

当使用这样的东西时:

private final Object lock = new Object()

静态和非静态有什么区别吗?

Is there any difference between static and non-static one?

非静态对象是否可以锁定静态方法,反之亦然?

Can non-static object lock static method or vice versa?

推荐答案

如果您使用的是非静态锁,则该对象的每个实例都会有一个不同的锁对象,这可能是更细粒度的等效项调用:

If you're using a non-static lock, every instance of the object would have a different lock object, and it would be a potentially more fine grained equivalent of calling:

synchronized(this) {

}

也就是说:您只是锁定来自同一对象内的其他访问.使用静态锁,类的每个实例都共享该锁对象.所以在任何给定时间只有一个线程可以访问同步块.

That is to say: you're only locking against other accesses from within the same object. With a static lock, every instance of the class shares that lock object. So only one thread can access the synchronized block at any given time.

所以这取决于你在做什么.在前一种情况下,分配锁对象没有意义,除非您有多个这些锁保护较小的数据子集.在后一种情况下,您基本上(再次,更细粒度)这样做:

So it depends on what you're doing. In the former case, it doesn't make sense to bother allocating a lock object unless you have multiple of these locks protecting a smaller subset of the data. In the latter case, you're basically (again, more fine grained) doing this:

synchronized(MyObject.class) {

}

也就是说,无论您有相同的对象还是不同的对象进行访问,您都会锁定所有访问.

That is, you're locking against ALL accesses regardless of whether you have the same object or different ones doing the accessing.

这取决于您要完成的任务、您锁定的对象以及这些锁的使用方式.如果您要保护每个实例状态,您可能需要一个每个实例(非静态)锁定对象.如果您要保护全局状态,您需要一个在所有人之间共享的静态锁对象.

It'll depend on what you're trying to accomplish, and what you're locking against, and how those locks are being used. If you're protecting per-instance state, you probably want a per instance (non-static) lock object. If you're protecting global state, you want a static lock object that's shared amongst everyone.

这篇关于使用synchronized(lock)时,锁对象最好是静态的还是非静态的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

更多推荐

[db:关键词]

本文发布于:2023-05-01 14:13:41,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1410447.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:静态   是非   对象   synchronized   lock

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!