ReentrantLock .lock

0

The lock method of the class ReentrantLock blocks the code that is enclosed by the lock and the unlock . If the code is already blocked, the next thread that tries to execute that code waits until it is unlocked or continues executing after unlock ?. Below I ask one more question.

public void transferir(int origen, int cFinal, double cantidad) {

    rt.lock();

    System.out.println("El thread: " + Thread.currentThread().getName() + " bloqueó el código." );

    try {
        if (cuentas[origen] < cantidad) {
            System.err.println("CANTIDAD INSUFICIENTE: Cuenta " + origen + ". Saldo: " + cuentas[origen] + ". Monto a transferir: " + cantidad );
            return;
        }else {
            System.err.println("Transferencia aceptada: ");
        }

        cuentas[origen] = cuentas[origen] - cantidad;

        System.out.printf("%10.2f de  %d para %d. ", cantidad, origen, cFinal);

        cuentas[cFinal] = cuentas[cFinal] + cantidad;

        System.out.printf("Saldo total: %10.2f\n", getSaldoTotal());
    } finally {
        System.out.println("El thread: " + Thread.currentThread().getName() + " desbloqueó el código." );
        rt.unlock();
    }

}

The out of the previous code:

El thread: Thread-0 bloqueó el código.
Transferencia aceptada: 
Transferencia aceptada: 
Transferencia aceptada: 
Transferencia aceptada: 
Transferencia aceptada: 
Transferencia aceptada: 
Transferencia aceptada: 
Transferencia aceptada: 
Transferencia aceptada: 
Transferencia aceptada: 
   2000,00 de  0 para 59. Saldo total:  200000,00
El thread: Thread-0 desbloqueó el código.

Why do you print several times "Transfer accepted:" ...?

    
asked by MatiEzelQ 02.03.2016 в 02:10
source

1 answer

2

The problem is not in the use of the lock but in the use of the stream to print to the console. In some cases you use System.out and in others System.err . Each of them are different streams that end up writing the information about the console, but they do it at different times and they do not have an exact order on which one will be shown first. To solve this, just use System.out in your code. It is not recommended to use System.err . Or better yet, use a logging library like logback or log4j2 to avoid using System.out and System.err .

    
answered by 02.03.2016 / 03:57
source