简体   繁体   中英

Executing threads in a sequence with semaphores

I'd like to execute some threads in a sequence using semaphores. There is no problem using a semaphore for every thread but I'd like to do it with using only one.

I think that the following code should work fine but sometimes it doesn't. I'd appreciate your help.

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

}

See this answer that explains why it may fail, eg, when there are only three permits available and the thread requiring four permits is the next one to be assigned permits. It also discusses various ways around this issue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM