用信号量执行线程



我想使用信号量执行序列中的某些线程。对于每个线程,使用一个信号量没有问题,但是我只想使用一个线程。

我认为以下代码应该可以正常工作,但有时效果不佳。感谢您的帮助。

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);
    }
}

}

请参阅此答案,其中解释了它可能失败的原因,例如,当只有三个许可证,并且需要四个许可证的线程是下一个要分配许可证的允许许可证。它还讨论了有关此问题的各种方式。

最新更新