import java.util.concurrent.*;
import java.util.concurrent.atomic.*;

/**
 * An example that illustrates the use of a CountDownLatch.
 *
 * @author  Prof. David Bernstein, James Madison University
 * @version 1.0
 */
public class LatchExample
{
    /**
     * The entry point of the application.
     *
     * @param args  The command-line arguments (which are ignored)
     */
    public static void main(String[] args)
    {
        Algorithm[]      algorithm;
        AtomicInteger    result = new AtomicInteger(-1);        
        CountDownLatch   latch  = new CountDownLatch(1);

        // Construct multiple algorithms to solve the same problem
        algorithm = new Algorithm[2];
        algorithm[0] = new GreedyAlgorithm(result, latch);
        algorithm[1] = new DynamicProgrammingAlgorithm(result, latch);
        
        // Start the algorithms
        for (int i=0; i<algorithm.length; i++)
        {
            (new Thread(algorithm[i])).start();
        }

        try
        {
            // Wait for either of the two algorithms to finish
            latch.await();
        
            // Get the result and continue processing
            int i = result.get();
            
            System.out.printf("Using %d\n", i);
        }
        catch (InterruptedException ie)
        {
            // Respond accordingly
        }
    }
}
