在研究线程池相关代码的过程中发现了jdk1.8下rt.jar/java/util/concurrent/ThreadPoolExecutor.java
中在addWorker()
里判断线程池使用状态时使用了:Label,break Label,continue Label。不禁想起golang中也有类似的使用。
Java中,一般通过break和continue只能影响一层循环,而通过声明Label配合continue Label以及break Label可以影响到多层循环。简单测试如下
public static void main(String [] args) { for(int i= 0; i < 3; i++){ System.out.println("outer print: index ["+ i+"]"); for (int j = 0; j<3; j++){ if (j == 1) { continue; } System.out.println("inner print: (" + j+")" ); } } System.out.println("========================"); outer: for (int i = 0 ; i<3 ; i++){ System.out.println("outer print: index ["+i+"]"); for (int j = 0 ; j<3; j++){ if (i == 2){ break outer; } if (j == 1) { continue outer; } System.out.println("inner print: ("+j+")"); } } }
输出结果
outer print: index [0] inner print: (0) inner print: (2) outer print: index [1] inner print: (0) inner print: (2) outer print: index [2] inner print: (0) inner print: (2) ======================== outer print: index [0] inner print: (0) outer print: index [1] inner print: (0) outer print: index [2]
可以观察到continue Labe和break Label直接影响到了外层循环。