//====================================================================
// Compute the future value of an annuity: 
// Synchronized threads accessing the same "static" shared fields/methods 
//====================================================================
public class Sync2static
{
    public static void main(String[ ] args)
    {
        Sync2staticThread obj1 = new Sync2staticThread (250, 3.50, 8);  //instantiate a pgm obj
        Sync2staticThread obj2 = new Sync2staticThread (250, 3.50, 8);

        Thread t1 = new Thread(obj1, "thread-1");                       //instantiate a thread 
        Thread t2 = new Thread(obj2, "thread-2");

        t1.start( );                                                    //start the thread
        t2.start( ); 
    }
}
//====================================================================
// A thread class - will be launched multiple times.  Accesses shared static data elements
//====================================================================
class Sync2staticThread  implements Runnable 
{
    double amount;
    double interest;
    int    years;
    static double futureValue;                                      //static computational field

    Sync2staticThread(double amount, double interest, int years)    //constructor
    {
        this.amount  = amount;
        this.interest  = interest;
        this.years     = years;
    }

    public void run( )
    {
        calc(amount, interest, years);

        Thread t = Thread.currentThread( );
        String  tName = t.getName( );

        System.out.println( "----------------------"            + "\n" +
                            tName                               + "\n" +
                            "Using static fields"               + "\n" +
                            "Future value of annuity:"          + "\n" +
                            "monthly amount=" + this.amount     +
                            " interest="      + this.interest   + "%"  +
                            " years="         + this.years      + "\n" +
                            "is ==> "         + futureValue     + "\n" +
                            "----------------------" );
      }

    static  synchronized  void  calc(double amount, double interest, int years)
    {
        int    months           = years * 12;
        double mthInterestRate  = interest/100 / 12;
        futureValue             = 0;

        Thread t = Thread.currentThread( );
        String  tName = t.getName( );

        for (int i = 1; i <= months; i++)
        {
            futureValue = (futureValue + amount) * (1 + mthInterestRate);
            System.out.printf("%s %s%2d %s%6.2f \n", tName," mth=",i," fv=",futureValue);
        }
    }
}