我的一本教科书提到,synchronized()的参数必须是这个...我知道这是错误的.但我听说,由于synchronized(this)更安全,所以应该总是使用它.真的吗 ?谢谢:)
不,它不一定总是如此.它也不能在静态方法的情况下,因为没有这个.
此外,有时也认为与此同步是错误的,因为锁定对象在外部可见.
public class Example {
private final Object lock = new Object();
// does not compile, there is no 'this' in static context.
public static void staticMethod() {
synchronized (this) {
}
}
public void method() {
int x = 3;
//there is risk that someone else outside our code
//uses same lock
synchronized (this) {
}
//this lock is private
synchronized (lock) {
}
}
}
Run Code Online (Sandbox Code Playgroud)