gpt4 book ai didi

java - java中的synchronized关键字仅仅是语法糖吗?

转载 作者:行者123 更新时间:2023-12-01 19:11:08 25 4
gpt4 key购买 nike

Possible Duplicate:
synchronized block vs synchronized method?

大家好,我想知道 Snippet-A 是否只是 Snippet-B 的语法糖? :

片段A:

public synchronized void F() {
//..code
}

片段B:

public void F() {
synchronized (this) {
//..code
}
}

或者更确切地说,上面两段代码到底有什么区别?

最佳答案

两者是相同的。请参阅§8.4.3.6 Java Language Specification的(JLS):

A synchronized method acquires a monitor before it executes. [...] For an instance method, the monitor associated with this (the object for which the method was invoked) is used.

在 JLS 的示例中,如下:

synchronized void bump() { count++; }

据说具有与此相同的效果:

void bump() {
synchronized (this) {
count++;
}
}

并且您的两个 F 方法与示例 bump 方法非常相似。

关于java - java中的synchronized关键字仅仅是语法糖吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8375880/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com