A propos de wait(), notify() et notifyAll
Bonjour,
Je commence par joindre les exemples et explique après :
Code:
1 2 3 4 5 6 7 8 9 10
|
class Station {
public synchronized void attendreBus() throws InterruptedException {
wait();
}
public synchronized void chargerUsagers() {
notifyAll();
}
} |
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
|
class Usager extends Thread {
private String nom;
private Station s;
private int heureArrivee;
public Usager(String nom, Station s, int heureArrivee) {
this.nom = nom;
this.s = s;
this.heureArrivee = heureArrivee;
}
public void run() {
try {
sleep(heureArrivee);
System.out.println(nom + " arrive a la station");
s.attendreBus();
System.out.println(nom + " est monte dans le bus");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} |
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
| class Bus extends Thread {
private Station s;
private int heureArrivee;
public Bus(Station s, int heureArrivee) {
this.s = s;
this.heureArrivee = heureArrivee;
}
public void run() {
try {
sleep(heureArrivee);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Bus arrive a la station");
s.chargerUsagers();
System.out.println("Bus repart de la station");
}
public static void main(String args[]) {
Station Gare = new Station();
Bus b7 = new Bus(Gare, 2000);
Usager u[] = { new Usager("Philippe", Gare, 1500),
new Usager("Patricia", Gare, 3000),
new Usager("Yves", Gare, 1000),
new Usager("Mireille", Gare, 1000) };
b7.start();
for (int i = 0; i < u.length; i++)
u[i].start();
}
} |
1- Première question sur le fonctionnement de notify()
notify prévient a une thread en attente (wait()) qu'elle peut continuer son traitement. Mais, cas de plusieurs thread en attente lequel démarre? Est-ce un au hasard ou le premier arrivé? ou est ce qu'il existe un mecanisme qui permets de lancer une thread spécifique?
J'ai un peu du mal a comprendre ce mécanisme.
2- Dans les exemples plus hauts, dans la classe Station, attendreBus et changerUsager sont des méthodes synchronised. Enlever synchronised envoi une exception IllegalMonitorStateException , pourquoi cela?
3- Et enfin pourquoi un simple appel de wait dans la classe Usager renvoi l'exception IllegalMonitorStateException