-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCuentaBancaria_Java
More file actions
78 lines (67 loc) · 2.4 KB
/
CuentaBancaria_Java
File metadata and controls
78 lines (67 loc) · 2.4 KB
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
66
67
68
69
70
71
72
73
74
75
76
77
78
class CuentaBancaria {
private double saldo;
private String nombreBanco;
CuentaBancaria(double saldo, String nombreBanco){
this.saldo = saldo;
this.nombreBanco = nombreBanco;
}
public synchronized double getSaldo() {
return this.saldo;
}
public synchronized void depositar (int idCliente, double cantidad){
System.out.printf("Cliente %d intenta depositar: %.2f euros\n", idCliente, cantidad);
double saldoAnterior = this.getSaldo();
this.saldo += cantidad;
System.out.printf("Cliente %d despositó: %.2f euros\n", idCliente, cantidad);
System.out.printf("Saldo anterior: %.2f euros, Nuevo saldo: %.2f euros\n\n", saldoAnterior, this.getSaldo());
}
public synchronized void retirar(int idCliente, double cantidad){
System.out.printf("Cliente %d intenta retirar: %.2f euros\n", idCliente, cantidad);
double saldoAnterior = this.getSaldo();
this.saldo -= cantidad;
System.out.printf("Cliente %d retiró: %.2f euros\n", idCliente, cantidad);
System.out.printf("Saldo anterior: %.2f euros, Nuevo saldo: %.2f euros\n\n", saldoAnterior, this.getSaldo());
}
}
class Cliente implements Runnable {
private final CuentaBancaria cuenta;
private int idCliente;
Cliente(CuentaBancaria cuenta, int idCliente){
this.cuenta = cuenta;
this.idCliente = idCliente;
}
@Override
public void run() {
for(int i = 0; i < 3; i++){
if(Math.random() < 0.5) {
cuenta.depositar(idCliente, 100);
}
else {
cuenta.retirar(idCliente, 100);
}
try {
Thread.sleep((long) Math.random()*1000);
} catch (Exception e) {
// TODO: handle exception
}
}
}
}
public class Banco {
public static void main(String[] args) {
CuentaBancaria cuenta = new CuentaBancaria(500, "BBVA");
Thread[] clientes = new Thread[5];
for(int i = 0; i < 5; i++){
clientes[i] = new Thread(new Cliente(cuenta, i+1));
clientes[i].start();
}
for(Thread cliente: clientes){
try {
cliente.join();
} catch (Exception e) {
// TODO: handle exception
}
}
System.out.println("Saldo final: " + cuenta.getSaldo());
}
}