Hi, I'm stuck in some parts of my program and now I have the next part of my program:
public class Relleus {
public static void main(String[] args) throws InterruptedException {
Testimoni c = new Testimoni();
int numMembres = 5; //la familia pot ser més gran o més petita
//Es creen el membres de la família, se'ls dona un nom i es posen a mirar la tele
Corredor[] membre = new Corredor[numMembres];
for(int i=1; i<numMembres; i++) {
membre[i] = new Corredor(c);
membre[i].setName("CORREDOR : "+i);
membre[i].start();
}
//Esperem que tots acabin de mirar la tele
for(int i=1; i<numMembres; i++) {
membre[i].join();
}
System.out.println("Carrera acabada!!");
}
}
public class Corredor extends Thread {
Testimoni comandament;
static int canal;
public Corredor(Testimoni c) {
comandament = c;
canal = 0;
}
@Override
public void run() {
// 3, 2, 1, go, go, go
System.out.println("Escriu go a la pantalla..");
int veces = comandament.agafa();
System.out.println(getName() + " esta corren");
//Mira la tele
try {
Thread.sleep((long) (Math.random() * 350) + 300); //utilitzem el mètode sleep per suspendre l'execució del Thread un temps aleatori de ms
} catch (InterruptedException e) {
System.out.println("Error!!!");
}
if (veces == 0 || veces == 1 || veces == 2) {
System.out.println("Pasa el testimoni al seguent corredor:");
//Deixa el comandament
comandament.deixa();
} else {
comandament.deixa();
}
{
}
}
}
public class Testimoni {
/*
* Modifiqueu i afegiu el codi necessari per implementar la classe
* Comandament.
*/
boolean avalible = true;
int PasarTest = 0;
synchronized int agafa() {
while (avalible == false) {
try {
wait();
} catch (InterruptedException e) {
}
}
avalible = false;
notify();
return PasarTest;
}
synchronized void deixa() {
avalible = true;
++ PasarTest;
notify();
}
}
I have an array that shows 4 runners.
runner 1 runner 2 runner 3 Runner 4
But when I show them on the screen, I mix them.
How can I avoid it?
Can you give me an idea?
They are threads and I'm a bit lost. Surely it is silly but I do not know how to put the truth ..
thanks!