java - 循环屏障无法实现同步

标签 java multithreading wait

public class Test {

    final int counter = 0; // it may be a different number
    int add = 0;

    public synchronized void testSync() throws InterruptedException {
        add++;
        if (add == counter) {
            add = 0;

            notifyAll();
        } else {
            while (add > 0) {

                wait();
            }
        }

    }
}

如何修复代码以使其工作?我需要使其作为循环屏障工作。

最佳答案

public class Test {
    final int counter = 0; // it may be a different number
    final CyclicBarrier barrier = new CyclicBarrier(counter);

    public void testSync() throws InterruptedException, BrokenBarrierException {
        barrier.await();
    }
}

关于java - 循环屏障无法实现同步,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31280779/

相关文章:

java - 在 intellij : how can i see the all thrown exceptions? 中调试多线程

swift - 如何在 Swift 中设置实时线程?

java - 覆盖 AWT 事件调度线程

angular - Angular Protractor 测试的异步性质与等待

javascript - jQuery:如何等到 fadeTo(或任何其他效果)完成后再执行代码

Java等待线程在通知后不会恢复

java - 获取我的日志轨迹的准确时间和日期

java - 如何使用 Mockito 正确测试 Spring Boot

JavaFX 在 ListView 中显示字符串附近的图像

multithreading - 多核服务器上的 mongodb map reduce