import java.util.concurrent.atomic.*;

/**
 * An implementation of Runnable that increases a mutable integer.
 *
 * This version uses the AtomicInteger class to show how it corrects
 * the problems of using shared mutable state.
 *
 * @author  Prof. David Bernstein, James Madison University
 * @version 2.0
 */
public class Counter implements Runnable
{
    private int                iterations;
    private AtomicInteger      mutable;
    
    /**
     * Explicit Value Constructor.
     *
     * @param mutable    The AtomicInteger to use
     * @param iterations The number of times to increment the AtomicInteger
     */
    public Counter(AtomicInteger mutable, int iterations)
    {
        this.mutable    = mutable;        
        this.iterations = iterations;        
    }
    
    /**
     * The code to run in the thread of execution.
     */
    public void run()
    {
        for (int i=0; i<iterations; i++)
        {
            mutable.incrementAndGet();
        }
        System.out.printf("Value: %d\n", mutable.get());
    }
}
