import java.util.concurrent.*;

/**
 * An example that uses a CyclicBarrier in the calculation of
 * moving averages.
 *
 * @author  Prof. David Bernstein, James Madison University
 * @version 1.0
 */
public class BarrierMovingAverageExample 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];

        // Create a CyclicBarrier (that will calculate the range when reached)
        RangeFinder   rf = new RangeFinder(ma, WINDOW, ARRAY_LENGTH-WINDOW);
        CyclicBarrier barrier = new CyclicBarrier(THREADS, rf);
        
        // 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);
            Barriered b = new Barriered(averager, barrier);            
            Thread worker = new Thread(b);
            worker.start();
        }
        
        System.out.println("main thread terminating...");        
    }
}
