需求:均衡的從數組裡依次取出每一個元素,環形數組
下面的代碼是從Netty的源碼(DefaultEventExecutorChooserFactory.java
)中,抽出來的;
package com.xingej.toolkit.array;
import java.util.concurrent.atomic.AtomicInteger;
//從數組裡依次取出每一個元素,形成一個環形數組
public class SelectElem {
private final AtomicInteger idx = new AtomicInteger(0);
private final String[] elems;
SelectElem(String[] elems) {
this.elems = elems;
}
// 均衡的從數組裡取出每一個元素
// 方式一
public String nextA(){
return elems[Math.abs(idx.getAndIncrement() % elems.length)];
}
// 方式二 位運算
public String nextB() {
return elems[idx.getAndIncrement() & elems.length - 1];
}
//測試
public static void main(String[] args) {
String[] elems = {"spark", "hive", "hadoop","lgy"};
SelectElem selectElem = new SelectElem(elems);
for (int i = 0; i
System.out.println("---->:\t" + selectElem.nextB());
}
}
}
代碼已經上傳到git上了。