package concurrent; import java.util.*; import java.util.concurrent.atomic.*; public class AtomicIntegerTest { public static class FakeAtomicInteger { private int value; int get() { return value; } int incrementAndGet() { return ++value; } } private AtomicInteger ai = new AtomicInteger(); //private FakeAtomicInteger ai = new FakeAtomicInteger(); int get() { return ai.get(); } void run() { for (int idx = 0; idx < 1000000; ++idx) { ai.incrementAndGet(); } } public static void runCase(int threadCnt) throws Exception { final AtomicIntegerTest aitest = new AtomicIntegerTest(); ArrayList threads = new ArrayList(); int idx; for (idx = 0; idx < threadCnt; ++idx) { Runnable runnable = new Runnable(){public void run(){aitest.run();}}; Thread thread = new Thread(runnable, String.format("%04d", idx)); threads.add(thread); } for (idx = 0; idx < threadCnt; ++idx) { threads.get(idx).start(); } for (idx = 0; idx < threadCnt; ++idx) { threads.get(idx).join(); } System.out.println(aitest.get()); } public static void main(String[] args) throws Exception { int cnt = 10; while (cnt-- > 0) runCase(4); } }