使用信号量按顺序执行线程

Executing threads in a sequence with semaphores

我想使用信号量按顺序执行一些线程。为每个线程使用信号量没有问题,但我想只使用一个。

我认为下面的代码应该可以正常工作,但有时却不能。非常感谢你的帮助。

package pruebasecuencia;

import java.util.concurrent.Semaphore;

public class PruebaSecuencia {
    Semaphore sem = new Semaphore(0);

    public void go() throws InterruptedException{
        final int N = 5;

        Process[] proc = new Process[N];

        for (int i = 0; i < proc.length; i++) {
            proc[i] = new Process(i, sem);
            proc[i].start();
        }

        for (int i = 0; i < proc.length; i++) {
            proc[i].join();
        }
        System.out.println("Ended simulation");
    }

    public static void main(String[] args) throws InterruptedException {
        new PruebaSecuencia().go();
    }
}


public class Process extends Thread{
    Semaphore sem;
    int id;

    public Process (int id, Semaphore sem){
        this.id = id;
        this.sem = sem;
    }

    @Override
    public void run(){
        try {
            sem.acquire(id);
            System.out.println("Process " + id + " executing");
            sleep (300);
            sem.release(id+1);
        } catch (InterruptedException ex) {
            Logger.getLogger(Proceso.class.getName()).log(Level.SEVERE, null, ex);
    }
}

}

参见 解释它可能失败的原因,例如,当只有三个许可可用并且需要四个许可的线程是下一个要分配许可的线程时。它还讨论了解决此问题的各种方法。