I have the following code:
public class UnitatFamiliar extends Thread {
Comandament comandament;
public UnitatFamiliar(Comandament c) {
comandament = c;
}
@Override
public void run() {
//Agafa el comandament
comandament.agafa();
int canal = (int) ((Math.random() * 5) + 1); //triem un canal al·leatoriament, entre el 1 i el 100
Comandament CanalFinal = new Comandament();
CanalFinal.setCanal(canal);
if (canal == comandament.getCanal()) {
comandament.setCanal(canal);
} else {
System.out.println(getName() + " està mirant el canal " + canal);
}
//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!!!");
}
//Deixa el comandament
comandament.deixa();
}
}
I have something wrong and I do not know what it can be. The idea is:
- Si el canal es diferente al canal que hay actualmente, muestra un mensaje.
- Si es igual, entonces no hagas nada.
The problem is that it always shows the channel ... what am I wrong?
--- EDIT WITH THE PART OF CODE THAT IS MISSING:
public class Comandament {
/*
* Modifiqueu i afegiu el codi necessari per implementar la classe
* Comandament.
*/
boolean avalible = true;
int canal;
public int getCanal()
{
return canal;
}
public void setCanal(int canal)
{
this.canal = canal;
}
synchronized void agafa() {
while (avalible == false) {
try {
wait();
} catch (InterruptedException e) {
}
}
avalible = false;
notify();
}
synchronized void deixa() {
avalible = true;
notify();
}
}