this
或 class
表达式的同步。
所报告的结构包括 synchronized
块以及对 wait()
、notify()
或 notifyAll()
的调用。
同步 this
或 class
表达式可能并非好主意,原因有几点:
替代做法是考虑在 private final
锁对象上同步,对该对象的访问可以完全控制。
示例:
public void print() {
synchronized(this) { // 警告: 对 'this' 的锁操作可能会产生不可预见的副作用
System.out.println("synchronized");
}
}