需求: 希望AtomicInteger在1-10000之间循环使用,到10000了就从1重新开始。
找了一段代码,测试了一下,OK。 测试程序:
import java.util.Random; import java.util.concurrent.atomic.AtomicInteger;
public class TestAtomInteger {
private final AtomicInteger i = new AtomicInteger(0);
public static void main(String[] args) { final TestAtomInteger m = new TestAtomInteger(); for (int t = 0; t < 10; t++) { Thread th = new Thread() { public void run() { for (int i = 0; i < 20000; i++) { System.out.println(Thread.currentThread().getName() + ":" + m.incrementAndGet()); try { Thread.sleep(new Random().nextInt(5)); } catch (InterruptedException e) { e.printStackTrace(); } } } }; th.setName("Thread " + t); th.start();
}
}
public final int incrementAndGet() { int current; int next; do { current = this.i.get(); next = current >= 10000 ? 1 : current + 1; } while (!this.i.compareAndSet(current, next));
return next; }
public final int decrementAndGet() { int current; int next; do { current = this.i.get(); next = current <= 0 ? 10000 : current - 1; } while (!this.i.compareAndSet(current, next));
return next; } }
|