Synchronisation des threads

anjoelus Messages postés 1 Date d'inscription samedi 4 décembre 2010 Statut Membre Dernière intervention 22 décembre 2010 - 22 déc. 2010 à 22:26
 Utilisateur anonyme - 23 déc. 2010 à 11:39
je voudrai mettre le thread TA en veille puis le reveiller avec TB mais ca ne marche pas, au final TA et TB restent bloqués. merci de votre aide...
//: Evenement.java
// Classe simulant la notion d'événement
// anjoelus 20/12/2010
public class Evenement extends Thread
{
static Boolean Etat; // etat de l'evenement
String nom;
public Evenement(String nom) {
Etat = Boolean.FALSE;
this.nom=nom;
}

public void run()
{
this.set();

this.reset();

this.attente();
System.out.println("reveil du thread "+this.nom);
}
public synchronized void set() {
Etat = Boolean.TRUE;
// debloque les threads qui attendent cet evenement:
System.out.println("mise a true du thread "+this.nom);
notify();
System.out.println("debloque les autres threads par le thread "+this.nom);
}
public synchronized void reset() {
Etat = Boolean.FALSE;
System.out.println("mise a false du thread "+this.nom);
}
public synchronized void attente() {
if(Etat==Boolean.FALSE) {
try {
System.out.println("met en veille le thread "+this.nom);
wait(); // bloque jusqu'a un notify()

}
catch(InterruptedException e) {};
}
}// fin attente


public static void main(String[] argc)
{
Thread TA = new Evenement("TA");
Thread TB = new Evenement("TB");

TA.start();
TB.start();
}
}// fin classe

1 réponse

Utilisateur anonyme
23 déc. 2010 à 11:39
Bonjour

C'est normal que tout se bloque comme start() appelle run() et ta méthode run() appelle attente() qui appelle wait() pour les 2 threads ce qui les bloque tous les 2. Un seul thread devrait appeler wait() de sorte que l'autre puisse appeler notify() pour le réveiller.









TUER : http://tuer.sourceforge.net/tuer.jnlp

yeah! vive java
0
Rejoignez-nous