一种JAVA线程轮训调度算法

话不多说,直接上代码(本算法转载自“并发编程网 http://ifeve.com”)。

 

public class CycleAtomicInteger {
private final static long PARK_TIME = 1000L * 1000;

private AtomicInteger counter = new AtomicInteger(0);

private int range;

public CycleAtomicInteger(int range) {
    if (range < 2)
        throw new IllegalArgumentException();
    this.range = range;
}

/**
 * 获取下个原子值
 *
 * @return
 */
public int next() {
    for (;;) {
        int c = counter.get();
        int next = (c + 1) % range;
        if (counter.compareAndSet(c, next)) {
            return c;
        } else {
            LockSupport.parkNanos(PARK_TIME);
        }
    }
}

}



原文链接:(http://ifeve.com/13840/)

你可能感兴趣的:(并发,轮训)