“隐式” java中的同步?
当我有这样的方法时,
public void unsynchronizedMethod(){
callSynchronizedMethod();
//dosomestuff after this line
}
这是否意味着在 unsynchronizedMethod() 方法中调用 callSynchronizedMethod() 后的所有内容都是隐式同步的?
when I have a method like
public void unsynchronizedMethod(){
callSynchronizedMethod();
//dosomestuff after this line
}
does it mean that all content, after calling callSynchronizedMethod() in the unsynchronizedMethod()-Method, is implicitly synchronized?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
不会。锁会在
callSynchronizedMethod()
结束时释放。No. The lock is released at the end of
callSynchronizedMethod()
.同步以简单的方式定义:
synchronized
方法:在该方法的执行中synchronized
块:在该块的执行中以下是相关摘录Java 语言规范第三版:
JLS 14.19
同步
声明synchronized
方法在语义上与应用于整个方法的synchronized
语句相同 (§JLS 8.4.3.6。锁可以从this
获取(如果它是实例方法)或类
与方法的类关联的对象(如果它是静态方法;您不能在静态上下文中引用此)。回答原来的问题,给出这个片段:
仅与关键部分的同步,早期同步不会产生任何挥之不去的影响。
是设计使然:您应该始终努力最大限度地减少
相关问题
Synchronization is defined in a straightforward manner:
synchronized
method: within the execution of that methodsynchronized
block: within the execution of that blockHere are the relevant excerpts from Java Language Specification 3rd Edition:
JLS 14.19 The
synchronized
Statementsynchronized
methods is semantically identical to asynchronized
statement applied to the whole method (§JLS 8.4.3.6. The lock is obtained from eitherthis
(if it's an instance method) or theClass
object associated with the method's class (if it's astatic
method; you can't refer tothis
in astatic
context).So to answer the original question, given this snippet:
Note that this is by design: you should always strive to minimize synchronization to only critical sections. Outside of those critical sections, there is no lingering effect from earlier synchronization.
See also
Related questions
不,不是。
同步意味着一次只有一个线程执行代码。
但是在 callSynchronizedMethod() 之后,线程可以同时以不同的顺序再次运行代码。
No, it's not.
Synchronized means that only one thread at a time will execute the code.
But after
callSynchronizedMethod()
the threads could run again over the code in different order, all at at the same time.不,不会有隐式同步。同步在块或函数范围内工作。同步块之外的任何内容都不会同步。
下面的示例代码表明了这一点。如果方法同步,它将始终打印 0。
如果同步,我的结果应该为 0:
No, there wont be an implicit synchronisation. Synchronized works within a block or function scope. Anything outside a synchronized block is not synchronized.
The following example code shows that. If the methods where synchronized it would always print 0.
My Results, should have been 0 if synchronized: