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
| public class VasesCommuniquants {
private static final int QUANTITE_INITIALE = 200;
public static final int NB_THREAD_MAX = 3;
private static int iteration =0;
private int [] vase = {QUANTITE_INITIALE/2, QUANTITE_INITIALE/2};
public VasesCommuniquants(){
for (int i=0;i < NB_THREAD_MAX;i++)
new ThreadTransfert().start();
}
public static void main(String[] args) {
new VasesCommuniquants();
}
public int transfert (int qte){
System.out.println("-("+qte+") dans la vase 1");
vase[0] -= qte;
System.out.println("+("+qte+") dans la vase 2");
vase[1] += qte;
iteration ++;
if(iteration % 100 == 0)
System.out.println(""+iteration+"itérations");
return vase[0]+vase[1];
}
public class ThreadTransfer extends thread {
Random r = new Random ();
int quantite;
public void run(){
while(!isInterrupted()){
quantite= r.nextInt(1L)=6;
if(transfert(quantite) != QUANTITE_INITIALE) {
System.out.println("Quantité totale invalide à l'itérartion"+iteration);
system.exit(-1);
}
try {
Thread.sleep(10);
}catch (InterruptedException e) {}
}
} |
Partager