我有两个线程,A
和B
。我想要以下内容:
A
等待B
开始执行f()
。 B
开始执行f()
之后,A也可以继续其工作。B
通知f()
的状态时A
已经在执行B
,则A
也可以继续工作。B
完成了f()
的执行,则A
必须等到B
以后再次开始执行f()
。在功能中:
// executed by A only
public void waitForB() throws InterruptedException {
// keep waiting until B starts f()
}
// executed within aroundF() only
public void f() {
}
// executed by B only
public void aroundF() {
// 1. mark that we are executing f() and inform A
f()
// 2. unmark
}
我一直在尝试使用Semaphore
,Phaser
和CyclicBarrier
,但是我很难理解在这里使用哪个。
我设法通过手动锁定实现了这一点(请参见下文),但是我想了解在这里使用哪个java.util.concurrent
类。
private final Object lock = new Object();
private boolean executing = false;
public void waitForB() throws InterruptedException {
synchronized(lock) {
while(!executing) {
lock.wait();
}
}
}
public void f() {
}
public void aroundF() {
try {
synchronized(lock) {
executing = true;
lock.notify();
}
f();
} finally {
executing = false;
}
}
答案 0 :(得分:1)
您可以使用java.util.concurrent.locks.Lock
和关联的java.util.concurrent.locks.Condition
实现相同的语义(以及更多),例如:
public class MyClass {
private final Lock lock = new ReentrantLock();
private final Condition condition = lock.newCondition();
private boolean executing = false;
public void waitForB() throws InterruptedException {
lock.lock();
try {
while (!executing) {
condition.await();
}
} finally {
lock.unlock();
}
}
public void f() {
}
public void aroundF() {
try {
lock.lock();
try {
executing = true;
condition.signal();
} finally {
lock.unlock();
}
f();
} finally {
executing = false;
}
}
}