【问题标题】:Free all waiting threads释放所有等待线程
【发布时间】:2016-11-05 15:07:03
【问题描述】:

我正在编写模拟障碍点的此类。当一个线程到达这个障碍点时,它不能继续,直到其他线程也到达这个点。我正在使用计数器来跟踪此时已到达的线程数。假设该类需要 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 行等待。

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

【问题讨论】:

  • this.cycle = !this.cycle; cv.signalAll();?
  • 如果这是一个可重用的屏障,您还必须决定在 freeAll 调用之后到达的线程应该发生什么,并且 freeAll 需要重置 this.count。

标签: java multithreading java-threads barrier


【解决方案1】:

更好的主意 - 使用标准 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()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-07-23
    • 1970-01-01
    • 2021-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-20
    • 1970-01-01
    相关资源
    最近更新 更多