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
| public class VaseComuniquant {
private static final int QUANTITE_INITIALE = 200;
private static final int NB_THREAD_MAX = 2;
private static int iteration = 0;
private int[] vase = {QUANTITE_INITIALE / 2,QUANTITE_INITIALE / 2};
public VaseComuniquant() {
for( int i = 0; i < NB_THREAD_MAX; i++)
new ThreadTransfert().start();
}
public static void main(String[] args) {
new VaseComuniquant();
}
public synchronized int transfert(int qte) {
// Ne pas enlever les System.out de ce test !
System.out.print("-("+qte+") dans le vase 1 ");
vase[0] -= qte;
System.out.println("+("+qte+") dans le vase 2");
vase[1] += qte;
iteration++;
if( iteration % 1000 == 0)
System.out.println("" + iteration + " itérations.");
return vase[0]+vase[1];
}
public class ThreadTransfert extends Thread {
Random r = new Random();
int quantite;
public void run() {
while( !isInterrupted()) {
quantite = r.nextInt(11)-6;
vase[0] -= quantite;
vase[1] += quantite;
if( transfert(quantite) != QUANTITE_INITIALE) {
System.err.println("Quantité totale invalide à l'itération " + iteration);
System.exit(-1);
}
try {
Thread.sleep(10);
} catch (InterruptedException e) {}
}
}
}
} |
Partager