1.匿名内部类中的变量捕获
public class App {
String s1 = "全局变量";
public void testInnerClass() {
String s2 = "局部变量";
new Thread(new Runnable() {
String s3 = "内部变量";
@Override
public void run() {
System.out.println(this.s3); //this关键字,表示的是当前内部类类型的对象
System.out.println(s1); //直接访问全局变量
System.out.println(s2); //直接访问局部变量,但是不能对局部变量进行修改,默认是final类型
}
}).start();
}
public static void main(String[] args) {
App app = new App();
app.testInnerClass();
}
}
2.lambda表达式中的变量捕获
public void testLambda() {
String s2 = "局部变量Lambda";
new Thread(() -> {
String s3 = "内部变量Lambda";
//访问全局变量
System.out.println(this.s1); //this关键字,表示就是所属方法所在类型对对象
//访问局部变量
System.out.println(s2); //不能局部修改,默认是final类型
System.out.println(s3);
}).start();
}
原文:https://www.cnblogs.com/freeht/p/13034597.html