0
セマフォを使用してシーケンス内のいくつかのスレッドを実行したいと思います。スレッドごとにセマフォーを使用することに問題はありませんが、私は1つだけを使用してそれをしたいと思います。セマフォを使用してシーケンス内のスレッドを実行する
私は次のコードはうまくいくはずだと思いますが、時にはうまくいきません。私はあなたの助けに感謝します。
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);
}
}
}
スレッドを順番に実行するポイントは何ですか? –
プロセス/スレッドのいずれかがidが1であると仮定します。セマフォがcount> = 1で解放されると、sem.acquire(1)を実行するプロセス/スレッドは、取得を保留中です。おそらく、プロセス/スレッドごとに1つのセマフォを使用しているかもしれません。 – rcgldr
プロセスごとに1つのセマフォを使用しても問題はありませんが、なぜこのコードが機能しないのか知りたいのですが。いくつかの実行では正常に動作しますが、アプリケーションがハングすることがあります。 – Alberto