1 retry发现位置
ThreadPoolExecutor
private boolean addWorker(Runnable firstTask, boolean core) {
retry:
for (;;) {
int c = ctl.get();
int rs = runStateOf(c);
// Check if queue empty only if necessary.
if (rs >= SHUTDOWN &&
! (rs == SHUTDOWN &&
firstTask == null &&
! workQueue.isEmpty()))
return false;
for (;;) {
int wc = workerCountOf(c);
if (wc >= CAPACITY ||
wc >= (core ? corePoolSize : maximumPoolSize))
return false;
if (compareAndIncrementWorkerCount(c))
break retry;
c = ctl.get(); // Re-read ctl
if (runStateOf(c) != rs)
continue retry;
// else CAS failed due to workerCount change; retry inner loop
}
}
}
2 测试retry用法
2.1 使用retry实现
/** 输出结果 0 1 2 3 */
@Test
public void testRetry1() {
retry:
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 4; j++) {
if (i == 1) {
// 跳转到retry位置, 这里的continue retry和break效果一样
// 如果不加retry, 内层循环会循环4次, 进行4次continue
continue retry;
}
if (i == 2) {
// 跳转到retry位置, 跳出两层循环, 相当于return
break retry;
}
System.out.print(j + " ");
}
}
}
2.2 不使用retry实现(和使用retry达到相同效果, 方便对比)
/** 输出结果 0 1 2 3 */
@Test
public void testRetry2() {
for (int i = 0; i < 3; i++) {
// 注意这里, 为了方便内层循环跳出两层循环, 定义变量
boolean flag = true;
for (int j = 0; j < 4; j++) {
if (i == 1) {
break;
}
if (i == 2) {
// 跳出两层循环
flag = true;
break;
}
System.out.print(j + " ");
}
if (flag) {
break;
}
}
}