Java8的final和effectively final

Java8之前,也就是Java没有lambda之前,在内部类内使用外部类的变量时,必须将变量置为final。

在有了lambda之后,对于在labmda函数内使用的外部变量的要求变松了,可以是“final”或者“有效的final”。有效的final意思是这个变量虽然没有显式的声明为final,但是实际上确实没有变更,编译就允许通过。示例如下

//可编译通过
for (int i = 0; i < 10; i++) {
    int counter = i;
    new Thread(() -> {
        System.out.println("i = " + counter);
    }).start();
}

//编译不通过
for (int i = 0; i < 10; i++) {
    int counter = i;
    new Thread(() -> {
        System.out.println("i = " + counter);
    }).start();
    counter++; //不通过是因为这里
}

原创文章,作者:geekgao,如若转载,请注明出处:https://www.geekgao.cn/archives/88

(0)
geekgaogeekgao博主
上一篇 2018年4月9日
下一篇 2018年7月29日

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注

GitHub
分享本页
返回顶部

Warning: error_log(/usr/local/lighthouse/softwares/wordpress/wp-content/plugins/spider-analyser/#log/log-2001.txt): failed to open stream: No such file or directory in /usr/local/lighthouse/softwares/wordpress/wp-content/plugins/spider-analyser/spider.class.php on line 2900