/**
 * An example that uses a multiple threads to calculate the moving average
 * of a data array.
 *
 * @author  Prof. David Bernstein, James Madison University
 * @version 1.0
 */
public class MultiThreadedMovingAverageExample extends AbstractMovingAverageExample
{
    /**
     * The entry point of the application.
     *
     * @param args  The command-line arguments (which are ignored)
     */
    public static void main(String[] args)
    {
        double[] data   = createData();
        double[] ma     = new double[data.length];
        Thread[] worker = new Thread[THREADS];

        // Create multiple threads to do the work and start them
        int work = ARRAY_LENGTH / THREADS;            
        for (int i=0; i<THREADS; i++)
        {
            Averager averager = new Averager(WINDOW, data, i*work, work, 
                                             ma);
            worker[i] = new Thread(averager);
            worker[i].start();
        }
        
        // Wait for all of the threads to terminate
        for (int i=0; i<worker.length; i++)
        {
            try
            {
                worker[i].join();
            }
            catch (InterruptedException ie)
            {
            }
        }

        // Calculate the range of the moving average in the main thread
        RangeFinder rf = new RangeFinder(ma, WINDOW, ARRAY_LENGTH-WINDOW);
        rf.run();
        
        System.out.println("main thread terminating...");
    }
}
