import java.util.concurrent.Semaphore; public class ATM { private static int balance = 0; private static int deposits = 0; private static int withdrawals = 0; static Semaphore semaphore = new Semaphore(1); // only one thread in the CS public void deposit() { try { semaphore.acquire(); balance ++; semaphore.release(); } catch (java.lang.InterruptedException e) {} } public void withdraw() { try { semaphore.acquire(); balance --; semaphore.release(); } catch (java.lang.InterruptedException e) {} } public int getBalance() { return balance; } public static void main(String[] args) { ATM atm = new ATM (); Thread A = new Thread (new Runnable() { public void run (){ while (true) { atm.deposit(); deposits ++; try { Thread.currentThread().sleep((int)(Math.random() * 1000)); } catch (InterruptedException e) {} System.out.println ("Thread A have made " + deposits + " deposits and see the balance as " + balance); } } }); Thread B= new Thread (new Runnable() { public void run (){ while (true) { atm.withdraw(); withdrawals++; try { Thread.currentThread().sleep((int)(Math.random() * 1000)); } catch (InterruptedException e) {} System.out.println ("Thread B have made " + withdrawals + " withdrawals and see the balance as " + balance); } } }); A.start(); B.start(); } }