package cmsc433.ex1;

import java.util.concurrent.atomic.AtomicInteger;

import junit.framework.TestCase;

public class TestAtomicInt extends TestCase {
	AtomicInteger goodai;

	private class IncThread extends Thread {
		BadAtomicInt ai;

		public IncThread(BadAtomicInt ai) {
			this.ai = ai;
		}
		public void run() {
			try {
				for(int i = 0; i < 1000; i++) {
					if(Math.random() < 0.1)
						sleep(1);
					ai.getAndIncrement();
					goodai.getAndIncrement();
				}
			} catch (InterruptedException e) {
				System.out.println("Interrupted");
			}
		}
	}

	public void testAtomicInt() throws InterruptedException {
		Thread[] threads = new IncThread[10];
		BadAtomicInt ai = new BadAtomicInt(0);
		goodai = new AtomicInteger(0);

		for(int i = 0; i < threads.length; i++) {
			threads[i] = new IncThread(ai);
			threads[i].start();
		}
		for(int i = 0; i < threads.length; i++)
			threads[i].join();
		assertTrue(goodai.get() == ai.get());
	}
}
