In summary mode, the result I get now is:
Miembro_X esta mirando el canal ...
Miembro_X esta mirando el canal ...
Miembro_X esta mirando el canal ...
Ja nadie mira la tv.
Code:
CASA CLASS:
public class Casa {
public static void main(String[] args) throws InterruptedException {
Comandament c = new Comandament();
int numMembres = 5; //total familia
UnitatFamiliar[] membre = new UnitatFamiliar[numMembres];
for(int i=0; i<numMembres; i++) {
membre[i] = new UnitatFamiliar(c);
membre[i].setName("Miembro_"+i);
membre[i].start();
}
for(int i=0; i<numMembres; i++) {
membre[i].join();
}
System.out.println("Nadie mira la tv");
}
}
UNIDADEFAMILIA CLASS
public class UnitatFamiliar extends Thread {
Comandament comandament;
static int canal;
public UnitatFamiliar(Comandament c) {
comandament = c;
canal = 0;
}
@Override
public void run() {
comandament.Agafa();
int canal = (int) ((Math.random() * 100) + 1);
System.out.println(getName() + " esta mirando el canal " + canal);
//Mirar la tele
try {
Thread.sleep((long) (Math.random() * 350) + 300);
} catch (InterruptedException e) {
System.out.println("Error!!!");
}
//Dejaa el mando
comandament.Deixa();
}
}
From here, the new class that is:
COMANDAMENT, with two methods Agafa()
and Deixa()
:
public class Comandament {
private boolean avalible = false;
Comandament() {}
void Agafa() {
while (avalible == false) {
try {
wait();
} catch (InterruptedException e) {
}
}
avalible = false;
notify();
}
void Deixa() {}
}
I need that the users when they take the comandament
"mando de la tv"
, only they can take it during X time (in this case it is already implanted Thread.sleep((long) (Math.random() * 350) + 300);
in the class UnitatFamiliar
.
That is to say that when another one watches the same channel, the program will not say anything, but when it changes of channel it must warn.
I'm pretty lost. Can you help me?