java笔记之——for循环continue/break+标签
前言
在学习线程池源码时发现for循环中有个未曾见过的写法,此文作为学习记录。
一、源码展示
属于线程池中创建线程的方法里:continue/break后带有一个标签“retry”。
ps:retry为标签名,可以自己定义不同的标签名。
二、代码演示(for循环中使用标签)
1.continue使用标签
代码如下:
// 未使用标签的代码,即普通写法
public static void testContinue() {
System.out.print("testContinue:");
for(int i = 0; i < 5; i++) {
for(int j = 0; j < 5; j++) {
System.out.print(j + ", ");
if(j == 3) {
continue;
}
}
}
System.out.println(" >>> OK");
}
// 输出:0, 1, 2, 3, 4, 0, 1, 2, 3, 4, 0, 1, 2, 3, 4, 0, 1, 2, 3, 4, 0, 1, 2, 3, 4, >>> OK
// 有使用标签(retry)的代码
public static void testRetryContinue() {
System.out.print("testRetryContinue:");
retry:
for(int i = 0; i < 5; i++) {
for(int j = 0; j < 5; j++) {
System.out.print(j + ", ");
if(j == 3) {
continue retry;
}
}
}
System.out.println(" >>> OK");
}
// 输出:0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, >>> OK
对比我们可以发现:
回顾一下continue(不带标签)的使用方法:continue 语句会终止本次循环,循环体中 continue 之后的语句将不再执行,接着进行下次循环。
而使用了标签(retry)后,continue语句会直接结束最内层的循环,外层循环进行下次循环(效果与不带标签的break相同)。
2.break使用标签
代码如下:
public static void testBreak() {
System.out.print("testBreak:");
for(int i = 0; i < 5; i++) {
for(int j = 0; j < 5; j++) {
System.out.print(j + ", ");
if(j == 3) {
break;
}
}
}
System.out.println(" >>> OK");
}
// 输出:0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, >>> OK
public static void testRetryBreak() {
System.out.print("testRetryBreak:");
retry:
for(int i = 0; i < 5; i++) {
for(int j = 0; j < 5; j++) {
System.out.print(j + ", ");
if(j == 3) {
break retry;
}
}
}
System.out.println(" >>> OK");
}
// 输出:0, 1, 2, 3, >>> OK
对比我们可以发现:
回顾一下break(不带标签)的使用方法:break 语句会直接结束最内层循环(即使用了break的for循环),外层循环接着进行下次循环。
使用了标签(retry)后,break语句会直接终止所有循环,即循环结束。
总结
continue+标签的作用与break相同;
break+标签能终止所有循环,即循环结束(这种场景可以少写代码)。
没有做更深入的学习,欢迎大佬在评论处留下珍贵的笔记。
Ps:感谢您的阅读,转载请标明出处(https://blog.csdn.net/qq_41099935/article/details/85990723)