实现说明
真正干活的是类 LockScopeMismatch、monitor、lock和函数 bumpWithClassLock、sleepQuietly,其余都是接线。
使用要点
- 每一步打印都带着自己的标签:
holder entered a's instance lock、holder still inside the critical section、b's instance lock taken while a's is held。 main按顺序串起bumpWithClassLock、sleepQuietly;运行文件就会把这个流程跑一遍。
常见问题
运行「实例锁与类锁互不排斥」会打印什么?
运行文件本身,holder entered a's instance lock、holder still inside the critical section、b's instance lock taken while a's is held 这些前缀各对应一段演示逻辑。
主要签名是 static void bumpWithClassLock()
核心语句
synchronized (LockScopeMismatch.class) { // the class monitor is a different lock
sharedTotal++;
}
synchronized (instanceLock) { // one monitor per object instance
sharedTotal++;
}
Thread.sleep(100); // let the holder enter first
synchronized (b.instanceLock) {
System.out.println("b's instance lock taken while a's is held");
}
代码示例
public class LockScopeMismatch {
private static int sharedTotal = 0;
private final Object instanceLock = new Object();
void bumpWithInstanceLock() {
synchronized (instanceLock) { // one monitor per object instance
sharedTotal++;
}
}
static void bumpWithClassLock() {
synchronized (LockScopeMismatch.class) { // the class monitor is a different lock
sharedTotal++;
}
}
public static void main(String[] args) throws InterruptedException {
LockScopeMismatch a = new LockScopeMismatch();
LockScopeMismatch b = new LockScopeMismatch();
a.bumpWithInstanceLock();
b.bumpWithInstanceLock();
bumpWithClassLock();
Thread holder = new Thread(() -> {
synchronized (a.instanceLock) {
System.out.println("holder entered a's instance lock");
sleepQuietly(300);
System.out.println("holder still inside the critical section");
}
});
holder.start();
Thread.sleep(100); // let the holder enter first
synchronized (b.instanceLock) {
System.out.println("b's instance lock taken while a's is held");
}
synchronized (LockScopeMismatch.class) {
System.out.println("class lock taken while a's instance lock is held");
}
holder.join();
System.out.println("sharedTotal = " + sharedTotal);
}
private static void sleepQuietly(long millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}