java - 释放所有等待线程

标签 java multithreading java-threads barrier

我正在编写模拟障碍点的此类。当一个线程到达此障碍点时,除非其他线程也到达此点,否则它无法继续进行。我正在使用一个计数器来跟踪此时已到达的线程数。假定该类期望使用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行等待。

有办法解决这个问题吗?我应该如何解决这个问题?

最佳答案

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

/**
 * 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()

关于java - 释放所有等待线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38175297/

相关文章:

java - 忽略了 Wildfly 安全约束

java - 如何在主方法中访问父类(super class)变量和方法?

java - spring如何在响应流中发送音频

java - 我可以知道java中Thread可运行类的属性吗?

javascript - 如何生成预填充的可填写 PDF、更改其内容并解析内容

java - BlackBerry 线程模型

c - 使用 C 使用 pic16f877a 同时运行多个函数

java - 具有重写方法的可重入锁?

java - 创建和丢弃运行线程的 JFrame

java - 两个短命线程 vs. Executor