Well, doAction2 needs to set a lockdown condition which doAction2 itself doesn't need, but which freezes any doAction1 calls.
This is considerably more complicated than it initially sounds because you're set up for a race condition.
Here is one strategy, using primitive operations:
private final Object locker = new Object();
private int a1 = 0, a2 = 0;
public void doAction1() {
synchronized (locker) {
//one central lock to avoid race conditions.
while (a1 > 0) locker.wait();
a2++;
}
try {
doAction1ForReal();
} finally {
synchronized (locker) {
a2--;
locker.notifyAll();
}
}
}
and the same for dA2. You can use Lock objects from j.u.c of course, but not sure how it would end up any cleaner - you want guarantees that you can't deadlock (where a1 and a2 are both non-0, that'd be a deadlock here). Pretty sure this take cannot possibly result in deadlock: a2 cannot possibly be incremented until a1 is 0.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…