等待另一个线程做某事

时间:2018-11-27 13:28:58

标签: java concurrency java.util.concurrent

我有两个线程,AB。我想要以下内容:

  • 我想让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 
}

我一直在尝试使用SemaphorePhaserCyclicBarrier,但是我很难理解在这里使用哪个。

我设法通过手动锁定实现了这一点(请参见下文),但是我想了解在这里使用哪个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;
    }
}

1 个答案:

答案 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;
    }
  }
}