Discussion of Activity 8.4 - Running the GoodThread and the BadThread

Sample solution

Code for class BankAccount:

public class BankAccount
{
   private int balance = 0;
   public synchronized void methodA()
   {
      System.out.println("Entering A - the balance is " +  balance);
      balance++;
      delay(50);
      balance--;
      System.out.println("Exiting A");
   }

   public synchronized void methodB()  // This method is now synchronized!
   {
      System.out.println("Entering B  - the balance is " + balance);
      balance++;
      delay(50);
      balance--;
      System.out.println("Exiting B");
   }

   private void delay(int n)
   {
      try
      {
         Thread.sleep(n);
      }
      catch(Exception e)
      {
         System.out.println(e);
      }
   }
}