先上实例:
/**
* @Author: ZhangHao
* @Description: RetryTest
* @Date: 2020/11/4 20:11
* @Version: 1.0
*/
public class RetryTest {
public static void main(String[] args) {
// retry:后必须紧接for循环
retry:
for(int l = 0;l < 3;l++){
for(int m = 0;m < 3;m++){
for(int n = 0;n < 3;n++){
System.out.println("n:" + n);
if(n == 1){
continue retry;
}
}
System.out.println("m:" + m);
}
System.out.println("l:" + l);
}
System.out.println("end");
}
}
结果:
n:0
n:1
n:0
n:1
n:0
n:1
end
continue retry是继续retry:后的循环,和continue所在的循环无关。
/**
* @Author: ZhangHao
* @Description: RetryTest
* @Date: 2020/11/4 20:11
* @Version: 1.0
*/
public class RetryTest {
public static void main(String[] args) {
retry:
for(int l = 0;l < 3;l++){
for(int m = 0;m < 3;m++){
for(int n = 0;n < 3;n++){
System.out.println("n:" + n);
if(n == 1){
break retry;
}
}
System.out.println("m:" + m);
}
System.out.println("l:" + l);
}
System.out.println("end");
}
}
结果:
n:0
n:1
end
break retry是退出retry:后的循环,和break所在的循环无关。
retry其实写成a:也行,不影响使用。只不过源码中是写的retry:。
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
}
}
boolean workerStarted = false;
boolean workerAdded = false;
Worker w = null;
try {
w = new Worker(firstTask);
final Thread t = w.thread;
if (t != null) {
final ReentrantLock mainLock = this.mainLock;
mainLock.lock();
try {
// Recheck while holding lock.
// Back out on ThreadFactory failure or if
// shut down before lock acquired.
int rs = runStateOf(ctl.get());
if (rs < SHUTDOWN ||
(rs == SHUTDOWN && firstTask == null)) {
if (t.isAlive()) // precheck that t is startable
throw new IllegalThreadStateException();
workers.add(w);
int s = workers.size();
if (s > largestPoolSize)
largestPoolSize = s;
workerAdded = true;
}
} finally {
mainLock.unlock();
}
if (workerAdded) {
t.start();
workerStarted = true;
}
}
} finally {
if (! workerStarted)
addWorkerFailed(w);
}
return workerStarted;
}
retry:至少从JDK8开始就有了。