捕获的变量是什么,其用途是什么,为什么需要它?
捕获的变量是已复制的变量,因此可以在嵌套类中使用。必须复制它的原因是对象可能在当前上下文中失效。它必须是
final(或
final在Java
8中是有效的),因此不会混淆是否会看到对变量的更改(因为它们不会出现)
注意:Groovy确实有此规则,对局部变量的更改可能意味着对封闭类中的值的更改,如果涉及多个线程,则尤其令人困惑。
捕获变量的示例。
public void writeToDatabase(final Object toWrite) { executor.submit(new Runnable() { public void run() { writeToDBNow(toWrite); } }); // if toWrite were mutable and you changed it now, what would happen !?}// after the method returns toWrite no longer exists for the this thread...
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)