Napisałem kod bariery dla trzech wątków:
public class Bariera {
static Semafor arrive1 = new Semafor(0);
static Semafor arrive2 = new Semafor(0);
static Semafor arrive3 = new Semafor(0);
public static void main(String[] args){
new Worker1();
new Worker2();
new Worker3();
}
static class Worker1 implements Runnable{
Worker1(){
new Thread(this, "Worker1").start();
}
public void run(){
try {
arrive1.V();
arrive1.V();
arrive2.P();
arrive3.P();
} catch (InterruptedException ex) {}
System.out.println("W1: przeszedlem bariere");
}
}
static class Worker2 implements Runnable{
Worker2(){
new Thread(this, "Worker2").start();
}
public void run(){
try {
arrive2.V();
arrive2.V();
arrive1.P();
arrive3.P();
} catch (InterruptedException ex) {}
System.out.println("W2: przeszedlem bariere");
}
}
static class Worker3 implements Runnable{
Worker3(){
new Thread(this, "Worker3").start();
}
public void run(){
try {
arrive3.V();
arrive3.V();
arrive1.P();
arrive2.P();
} catch (InterruptedException ex) {}
System.out.println("W3: przeszedlem bariere");
}
}
static class Semafor{
private int Sem;
public Semafor (int ini){Sem = ini;}
synchronized public void V(){
++Sem;
notify();
}
synchronized public void P() throws InterruptedException{
while (Sem==0) wait();
--Sem;
}
}
}
Jednak chcę mieć kod uniwersalny na liczbę wątków, czyli n. Jakie zmiany proponujecie? Muszę stworzyć listę wątków i listę semaforów?
Nie chodzi o wzbogacenie programu o nowe elementy typu BlockingQueue, tylko uogólnienie mojego kodu dla n-wątków.