我想使用信号量在序列中执行一些线程。使用信号量对于每个线程都没有问题,但我只想使用一个。
我认为以下代码应该可以正常工作,但有时则不然。我很感激你的帮助。
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);
}
}
}