我想不通为什么在 lambda 表达式中捕获的变量是最终的或有效的最终变量。我看了这个问题,真的没有得到答案。
这个变量捕获是什么?
当我为我的问题搜索解决方案时,我读到这些变量是最终的,因为并发问题。但是对于这种情况,我们为什么不能用reentrant lock对象锁定 lambda 中的任务代码。
public class Lambda {
private int instance=0;
public void m(int i,String s,Integer integer,Employee employee) {
ActionListener actionListener = (event) -> {
System.out.println(i);
System.out.println(s);
System.out.println(integer);
System.out.println(employee.getI());
this.instance++;
employee.setI(4);
integer++;//error
s="fghj";//error
i++;//error
};
}
}
Run Code Online (Sandbox Code Playgroud)
在这个特定的代码中,我想知道为什么最后三个语句给出错误的原因,以及为什么我们要变异,Employee因为它是一个局部变量。(Employee 只是一个带有 getter 和 setter 的类int i。)
我也想知道为什么我们也可以变异this.instance。
我感谢对我上面提到的所有事实的完整详细回答。