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 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
| public class Main {
public static void main(String[] args) {
final Calcul t = new Calcul();
Thread t2 = new Thread() {
public void run() {
System.out.println("Début du thread 2");
synchronized(t) {
System.out.println("Début du synchronized du thread 2");
System.out.println("Avant le wait() dans le thread 2");
while ( t.isFinished()==false ) {
try { t.wait(); } catch(InterruptedException e) {System.out.printf("nari nari nari");}
}
System.out.println("Après le wait() dans le thread 2");
System.out.println(t.getSomme());
System.out.println("Fin du synchronized du thread 2");
}
System.out.println("Fin du thread 2");
}
};
t.start();
t2.start();
}
}
class Calcul extends Thread {
private volatile boolean finished = false;
public void run() {
System.out.println("Début du thread 1");
synchronized(this) {
System.out.println("Début du synchronized du thread 1");
for(int i = 0;i<100;i++) {
somme+=i;
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("Avant le notifyAll() dans le thread 1");
finished = true;
this.notifyAll();
System.out.println("Après le notifyAll() dans le thread 1");
System.out.println("Fin du synchronized du thread 1");
}
System.out.println("Fin du thread 1");
}
private int somme;
public int getSomme() {
return somme;
}
public boolean isFinished() {
return finished;
}
}; |