Java 并发障碍示例死锁

Java concurrency barrier example deadlock

我正在尝试实现自定义 Barrier 示例,以便在 Java 中了解有关并发的更多信息。我有一个可运行的 class:

public class Barrier implements Runnable {

    private static Semaphore barrier = new Semaphore(0);
    private static int toWait = 5;
    private static int counter = 0;

    private static long sleepTime;

    public static int ID = 0;

    private int id = ++ID;

    public Barrier(long sleep){
        sleepTime = sleep;
    }

    @Override
    public void run() {

        try {

            Thread.sleep(sleepTime);

            counter++;
            if (counter == toWait){
                barrier.release(counter);
            }
            barrier.acquire();

            System.out.println("Thread with sleep: " + id + " proceeds");

        } catch (InterruptedException ex) {
            Logger.getLogger(Barrier.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

}

然后在 main 函数中,我创建了 5 个线程并启动它们。 运行 我陷入僵局,无法解决。有人可以告诉我我做错了什么吗?

查看文档:

Acquires a permit, if one is available and returns immediately, reducing the number of available permits by one.

If no permit is available then the current thread becomes disabled for thread scheduling purposes and lies dormant until one of two things happens:

Some other thread invokes the release() method for this semaphore and the current thread is next to be assigned a permit; or Some other thread interrupts the current thread.

因此,由于您 aquire 对所有线程进行了一次处理,并且其中 none 已被释放,因此它们都将保持获取状态。也许将它们的计数器设置为 5。因此您释放最后一个元素并通过这样做删除其他元素的获取状态。

编辑:哦,你的信号量有 0 个许可。根据您的情况用 1 或 2 初始化它。

没有互斥。为了解决它,我需要添加另一个信号量并用 acquire release 包围计数器增量。