当使用static的时候,线程执行的时候会在线程栈里为其添加一个copy,以后引用的就是线程栈内的变量。使用final或直接使用true,感觉是一回事,这个变量就不是变量了,而是一个固定的值,boolean就两个值,在虚拟机启动的时候就确定了,存储位置应该也是在一个固定的区域(perm)了。因为访问栈内数据的速度要快于访问那个‘固定区域’的速度,所以就出现了你得到的结果啦。
还有,final对性能的提升主要是针对方法来说的,它能使得在编译的时候就确定哪个方法会被访问而不是动态绑定。所谓的性能提升就表现在这里,提升的有限。举个例子:
public class Maxes {
static volatile long index = 0;
public static void main(String[] args) throws InterruptedException{
final Person ps = new Student();
new Thread(){
public void run() {
while(true){
ps.say();
}
};
}.start();
Thread.sleep(1000);
System.out.println(index);
Thread.sleep(1000);
System.out.println(index);
Thread.sleep(1000);
System.out.println(index);
System.exit(0);
}
}
class Person{
public void say(){
Maxes.index ++;
}
}
class Student extends Person{
public final void say(){
Maxes.index ++;
}
}
//120076985
//169933373 final时候的表现