有不同级别的同步吗?
我听说同步有不同级别。有吗?(如果有,请用片段代码解释一下吗?)谢谢。
I have heard that there are different levels of Synchronization.are there?(If there are ,would you please explain them with a snippet code?)thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在 Java 5 之前,只有一个:
synchronized
关键字。这等待并获得了引用对象的独占锁。当应用于函数时:同步的对象是
this
。Java 5 添加了很多并发实用程序,其中之一是
锁定
对象。有多个版本,包括读写锁
。这是我能想到的唯一你可能提到的事情。synchronized
的问题在于它相当粗糙。做得不好可能会导致僵局。 Java 5 utils 允许非阻塞锁获取、锁获取超时和读/写锁支持。Before Java 5 there was only one: the
synchronized
keyword. This waited for and obtained an exclusive lock on the reference object. When applied to a function:the object being synchronized on is
this
.Java 5 added a lot of concurrency utils, one of which was the
Lock
object. There are several versions of this including aReadWriteLock
. This is the only thing I can think of that you might be referring to.The problem with
synchronized
is that its fairly crude. Done badly it can lead to deadlocks. The Java 5 utils allow non-blocking lock acquisition, timeout on lock acquisition and read/write lock support.您确实需要解释“同步级别”的含义。 之间的区别吗
您是在谈论:和
?或者也许在上述内容和使用 java.util.concurrent.locks?
如果您能提供更多您所听到的背景信息,我们也许能够为您提供更好的帮助。更重要的是,您认为可能需要此信息来尝试解决什么问题?
You'd really need to explain what you meant by a "level of synchronization". Are you talking about the difference between:
and
? Or perhaps between the above and using the locks from java.util.concurrent.locks?
If you could give more context to what you've heard, we may be able to help you better. More importantly, what problem are you trying to solve that you think might need this information?
我假设 OP 指的是多线程中使用的对象同步,而不是 Java 中的关键字。
这是我在阅读 Goetz 后对不同级别的同步的理解爪哇。
假设我们有一个必须在 132 个线程中使用的对象,这些线程连续、完全随机地使用该对象,比如说 100 年。
现在可能有不同的实现,无论是出于设计还是由于粗心,在不同级别上都是线程安全的。
如果这是一个真正的问题,则大多数实际实现属于“同步”的第四类,即它有时有效,并且没有足够的文档来分类为上述类别之一,因此默认属于第四类。
I am assuming OP is referring to synchronization of object used in multiple thread and not the keyword in Java.
This is my understanding, after reading Goetz, of different levels of synchronizations in Java.
Lets assume we have a object that we have to use across 132 threads, which use the object continuously, purely randomly, over say 100 years.
Now there could be different implementation which either by design or by carelessness, be thread safe at different levels.
If this were a real problem, the majority of the practical implementation falls in fourth category of 'synchronization', which is it works sometimes, and not documentation sufficiently to categorize in one of the above categories, and hence by default falls in fourth category.