import java.util.concurrent.locks.ReentrantLock;

public class ReentrantLockDasar {
    private static class Kas {
        private long saldo = 0;
        private final ReentrantLock kunci = new ReentrantLock();

        void setor(long jumlah) {
            kunci.lock(); // minta lock; menunggu bila sedang dipegang thread lain
            try {
                saldo += jumlah; // critical section
            } finally {
                kunci.unlock(); // WAJIB dilepas apa pun yang terjadi
            }
        }

        long bacaSaldo() {
            kunci.lock();
            try {
                return saldo;
            } finally {
                kunci.unlock();
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        Kas kas = new Kas();
        Runnable tugas = () -> {
            for (int i = 0; i < 100_000; i++) {
                kas.setor(1);
            }
        };
        Thread a = new Thread(tugas, "teller-A");
        Thread b = new Thread(tugas, "teller-B");
        a.start();
        b.start();
        a.join();
        b.join();
        System.out.println("saldo akhir: " + kas.bacaSaldo());
    }
}
