2

我正在写这个模拟障碍点的类。当一个线程到达这个障碍点时,它不能继续,直到其他线程也到达这个点。我正在使用计数器来跟踪此时已到达的线程数。假设该类需要 N+1 个线程,但只给出了 N 个线程。在这种情况下,程序将让所有线程等待,因为它认为还有一个线程要到达。

我想写一个方法,不管程序是否认为还有更多的线程要到达障碍点,我都可以释放所有等待的线程。

我的程序等待所有线程,

public volatile int count;
public static boolean cycle = false;

public static Lock lock = new ReentrantLock();
public static Condition cv = lock.newCondition();

public void barrier() throws InterruptedException {
    boolean cycle;
    System.out.println("lock");
    lock.lock();
    try {
        cycle = this.cycle;
        if (--this.count == 0) {
            System.out.println("releasing all threads");
            this.cycle = !this.cycle;
            cv.signalAll();
        } else {
            while (cycle == this.cycle) {
                System.out.println("waiting at barrier");
                cv.await(); // Line 20
            }
        }
    } finally {
        System.out.println("unlock");
        lock.unlock();
    }
}

我在想我可以简单地创建一个调用该signalAll()方法的方法,并且所有线程都是空闲的。但是,我遇到的一个问题是,如果程序需要更多线程,它将保持锁定,因为它将在第 20 行等待。

有没有办法绕过这个锁?我应该如何解决这个问题?

4

1 回答 1

0

更好的主意 - 使用标准 java.util.concurrent 原语 - CyclicBarrier 和方法'reset':

/**
 * Resets the barrier to its initial state.  If any parties are
 * currently waiting at the barrier, they will return with a
 * {@link BrokenBarrierException}. Note that resets <em>after</em>
 * a breakage has occurred for other reasons can be complicated to
 * carry out; threads need to re-synchronize in some other way,
 * and choose one to perform the reset.  It may be preferable to
 * instead create a new barrier for subsequent use.
 */
public void reset()
于 2016-07-04T18:14:51.027 回答