// this code implements a synchronized method deposit() that locks the for all
// other threads till the one that picked it is over

public class AccountDemo3
{
  public static void main(String[] args)
  {
    Account3 account = new Account3();

    Thread[] threads = new Thread[100];
    ThreadGroup g = new ThreadGroup("group");  // create a group of threads
    for (int i=0; i<100; i++)    // create and launch 100 threads
    {
      threads[i] = new Thread(g, new AddPennyThread3(account), "t");
      threads[i].start();
    }

    boolean done = false;
    while (! done)               // wait till all threads in the group
      if (g.activeCount() == 0)  // are stopped
        done = true;
                                 // print out the balance
    System.out.println("Balance = " + account.getBalance());
  }
}

class AddPennyThread3 extends Thread // a thread for adding 1c to the account
{
  private Account3 account;           // shared object for all threads

  public AddPennyThread3(Account3 account)  
  {
    this.account = account;          // assign account to the thread
  }

  public void run()                  // make the deposit
  {
    account.deposit(1);
  }
}

class Account3                       // shared object for all threads
{
  protected static int balance = 0;

  public int getBalance()
  {
    return(balance);
  }

  public synchronized void deposit(int amount)
  {
    int newBalance = balance + amount;

    try                             // "emulation" of a longer code
    {                               // that runs approx. 1 msec
      Thread.sleep(1);
    }
    catch(InterruptedException e){}
  
    balance = newBalance;
  }
}


