package concurrent; import java.util.*; import java.util.concurrent.atomic.*; public class AtomicIntegerLimit { private AtomicInteger ai = new AtomicInteger(1); private int limit; public AtomicIntegerLimit(int limit) { this.limit = limit; } public int getInt() { for (;;) { int i = ai.get(); int j = i + 1; if (i == limit) j = 1; if (ai.compareAndSet(i, j)) { return i; } } } public static void main(String[] args) throws Exception { int limit = 20; int threadCnt = 10; final int loopCnt = 1000; final AtomicIntegerLimit ait = new AtomicIntegerLimit(limit); final ArrayList intList = new ArrayList(); ArrayList threadList = new ArrayList(); for (int tidx = 0; tidx < threadCnt; ++tidx) { Thread thread = new Thread() { public void run() { for (int idx = 0; idx < loopCnt; ++idx) { int va = ait.getInt(); synchronized (intList) { intList.add(va); } } } }; thread.start(); threadList.add(thread); } for (Thread thread: threadList) thread.join(); for (int idx = 1; idx <= limit; ++idx) { int cnt = 0; for (Integer integer: intList) { if (idx == integer) ++cnt; } System.out.println("" + idx + ":" + cnt); } } }