1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
private void test() {
final String str = "23";
Thread t= new Thread(new Runnable() {
public void run() {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}


System.out.println("str:"+str);

}
});

t.start();
}

test()是一个类的方法,Runnable是它的匿名内部类,局部变量str用了final修饰符,如果没有final修饰符将会报错,为什么呢?

为了保证数据的一致。
从虚拟机运行内存角度:
test()方法对应虚拟机栈中的一个栈帧,当该栈帧出栈后其局部变量也就销毁,然这时存在内部类的方法需要访问str,就出现了生命周期不一致的情况,所以需要使用final将str变为常量来保证一致性。

匿名内部类编译后会另外单独生成一个Class,外部参数会以构造函数参数传入,传入参数可能在内部被修改,这会导致了数据的不一致。