//当出现要平均的返回某几个值的时候
public static AtomicInteger n = new AtomicInteger(0);
public static String[] nums = new String[]{"123","234", "345", "456"};
public final static int getNext(int size) {
int cur;
int next;
for (; ; ) {
cur = n.get();
next = (cur + 1) % size;
if (n.compareAndSet(cur, next)) {//如果设置成功了,就得到了想要的值。
// System.out.println("第几次访问:"+n.get());
return next;
}
}
}
平均分配问题
最新推荐文章于 2025-12-20 20:19:18 发布
这篇博客介绍了如何利用AtomicInteger类在Java中实现一个并发安全的轮询算法,该算法用于在给定大小的数组中获取下一个值。通过无限循环和compareAndSet方法确保线程安全,避免数据竞争。
935

被折叠的 条评论
为什么被折叠?



