场景: AtomicInteger原子增长计数,每个线程平均获取资源。到达临界值后,尝试恢复到取模区间0~7。经过测试,200次|500次调用分别出现一例apiCall:8。
@Test
public void test(){
AtomicInteger apiCallCount = new AtomicInteger();
ThreadFactory namedThreadFactory = new ThreadFactoryBuilder()
.setNameFormat("demo-pool-%d").build();
String[] apikeys="a,b,c,d".split(",");
//Common Thread Pool
ExecutorService pool = new ThreadPoolExecutor(1000, 1000,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>(1024), namedThreadFactory, new ThreadPoolExecutor.AbortPolicy());
CompletionService completionService = new ExecutorCompletionService<>(pool);
int times=200;
for(int i = 0; i < times; i++) {
final int j = i;
completionService.submit(new Callable() {
@Override
public String call() throws Exception {
try {
String[] tempApiKeys=apikeys;
int apiCall = apiCallCount.getAndIncrement();
if (apiCall >= 7) {
apiCallCount.compareAndSet(apiCall + 1, (apiCall + 1) % tempApiKeys.length);
}
if (apiCall < 0) {
apiCall = apiCall % tempApiKeys.length + tempApiKeys.length - 1;
}
String apikey = tempApiKeys[apiCall % tempApiKeys.length];
System.out.println("apikey:"+ apikey+",apiCall:"+ apiCall+","+j);
} catch (Exception e) {
e.printStackTrace();
}
return "OK";
}
});
}
pool.shutdown();//gracefully shutdown
for (int i = 0; i < times; i++) {
Future<String> future = null;
try {
future = completionService.take();
String result = future.get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
}
apikey:a,apiCall:0,76
apikey:c,apiCall:2,74
apikey:d,apiCall:3,89
apikey:b,apiCall:5,71
apikey:d,apiCall:7,69
apikey:b,apiCall:1,67
apikey:c,apiCall:2,66
apikey:a,apiCall:4,63
apikey:d,apiCall:7,61
apikey:b,apiCall:1,60
apikey:c,apiCall:2,58
apikey:a,apiCall:8,92