在看 ThreadPoolExecutor 源码时看到这么一段代码
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 } }
break 和 continue 分开测试
retry: for (;;) { System.out.println("A"); for (;;) { System.out.println("B"); break retry; } } System.out.println("End");
retry: for (; ; ) { System.out.println("A"); for (; ; ) { System.out.println("B"); continue retry; } }
会无限循环
总结
retry 并不是一个关键字,只是作为一个标记使用。并与最近的一个循环绑定,在使用 break 或 continue 时后面可加上该标记,就可指定对哪一层循环进行操作了