// this code demonstrates one way for creating threads by extending the
// Thread object
// Run it several times. The expected balance should be 100, but it never
// happens.

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

    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 AddPennyThread1(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 AddPennyThread1 extends Thread // a thread for adding 1c to the account
{
  private Account account;           // shared object for all threads

  public AddPennyThread1(Account account)  
  {
    this.account = account;          // assign account to the thread
  }

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

class Account                        // shared object for all threads
{
  private int balance = 0;

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

  public 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;
  }
}
