gpt4 book ai didi

java - 在 "this"或 Java 中的私有(private)对象上同步?

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:18:30 25 4
gpt4 key购买 nike

<分区>

Possible Duplicate:
Avoid synchronized(this) in Java?

这两段代码有什么区别?各有什么优缺点?

1)

public class Example {
private int value = 0;

public int getNextValue() {
synchronized (this) {
return value++;
}
}
}

2)

public class Example {
private final Object lock = new Object();
private int value = 0;

public int getNextValue() {
synchronized (lock) {
return value++;
}
}
}

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