/*monitores*/
import java.io.*;
class banco extends MyObject{
private ConditionVariable deposita = null;
private ConditionVariable retira = null;
private int cantidad;
public banco(){
deposita = new ConditionVariable();
retira = new ConditionVariable();
cantidad = 10000;
}
public synchronized void dep(int x){
while/*if*/((cantidad + x) >= 10000){
System.out.println("No se puede depositar ");
wait(deposita);
}
//else{
cantidad = cantidad + x;
System.out.println("Se ha depositado: " +x);
notify(retira);
//}
}
public synchronized void ret(int x){
while/*if*/((cantidad - x) <= 0){
System.out.println("No se puede retirar ");
wait(retira);
}
// else{
cantidad = cantidad - x;
System.out.println("Se ha retirado: " +x);
notify(deposita);
// }
}
}
class cliente1 extends Thread{
private banco caja1;
public cliente1(banco x) {this.caja1 = x;}
public void run(){
int cantidad;
for(int i=0;i<5;i++){
do
cantidad = ( (int)(Math.random()*3000) );
while(cantidad<1 || cantidad>10000);
//System.out.println("Retirando:"+cantidad);
caja1.ret(cantidad);
//System.out.println("Dinero: " + caja1.regresa());
try {sleep( (int)(Math.random()*10000) );}
catch(InterruptedException e){
System.out.println("Error:"+e.toString());}
}
}
}
class cliente2 extends Thread{
private banco caja2;
public cliente2(banco x) {this.caja2 = x;}
public void run(){
int cantidad;
for(int i=0;i<5;i++){
do
cantidad = ( (int)(Math.random()*3000) );
while(cantidad<=0 || cantidad>=1000);
//System.out.println("Ingresando:"+cantidad);
caja2.dep(cantidad);
//System.out.println("Dinero: " + caja2.regresa());
try {sleep( (int)(Math.random()*1000) );}
catch(InterruptedException e){
System.out.println("Error:"+e.toString());}
}
}
}
class cajeroAutomatico{
public static void main(String[] args){
banco b = new banco();
cliente1 c1 = new cliente1(b);
cliente2 c2 = new cliente2(b);
c1.start();
c2.start();
}
}
|