您可以使用比同步语句更灵活的Lock和Condition.
对于您的示例,您可以将obj2替换为ReentrantLock:
@H_403_8@Lock lock2 = new ReentrantLock();
try {
// Blocks until the lock is acquired,just like a `synchronized` statement
lock2.lock();
f1();
synchronized (obj1) {
f2();
lock2.unlock();
obj1.wait();
lock2.lock();
}
}
// Use `finally` to make sure the lock is always released,even if an exception is thrown
finally {
// Exception might have been thrown before current thread could acquire lock again,cannot
// unlock then
if (lock2.isHeldByCurrentThread()) {
lock2.unlock();
}
}
但是,这将允许另一个线程在当前线程开始等待obj1之前获取lock2.如果不希望这样,可以将obj1替换为Lock并等待obj2.