測(cè)試代碼:
public class IntegerTest {
public static void main(String[] args) {
Integer i1 = 12;
Integer i2 = 12;
Integer i3 = 135;
Integer i4 = 135;
System.out.println("i1 == i2? " + (i1 == i2));
System.out.println("i3 == i4? " + (i3 == i4));
}
}
輸出結(jié)果:
i1 == i2? true
i3 == i4? false
為什么都是Integer類的對(duì)象會(huì)輸出不同的結(jié)果呢皮获?
是因?yàn)镮nteger類的內(nèi)部做了緩存處理惫企,在Integer內(nèi)部有一個(gè)IntegerCache的靜態(tài)內(nèi)部類逐哈,該內(nèi)部類中會(huì)緩存-128到127的整數(shù)书释。當(dāng)用一個(gè)int類型的變量給Integer時(shí)竟贯,會(huì)使用自動(dòng)裝箱的程序盗誊。
public final class Integer extends Number implements
Comparable<Integer> {
...
private static class IntegerCache {
static final int low = -128;
static final int high;
static final Integer cache[];
...
cache = new Integer[(high-low)+1];
int j = low;
for(int k = 0;k < cache.length;k ++)
cache[k] = new Integer(j++);
...
}
...
//自動(dòng)裝箱的程序
public static Integer valueOf(int i) {
if(i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i+(-IntegerCache.low)];
return new Integer(i);
}
...
}
為了進(jìn)一步深入地理解Integer中的玄機(jī)圣猎,可以增加一下難度士葫,使用synchronized關(guān)鍵字進(jìn)一步驗(yàn)證。
public class ThreadA {
static Integer integer = 8;
public static void main(String[] args) throws InterruptedException{
ThreadB b =new ThreadB();
b.start();
synchronized (integer) {
System.out.println("deng dui xiang b wan cheng b wan
cheng ....");
integer.wait();
System.out.println("b dui xiang zong he shi :" + b.total);
}
}
}
class ThreadB extends Thread {
int total;
Integer integer = 8;
@Override
public void run() {
synchronized (integer) {
for(int i = 0;i < 101;i ++) {
total += i;
}
integer.notify();
System.out.println("computing is finished");
}
}
}
輸出結(jié)果
deng dui xiang b wan cheng b wan cheng ....
computing is finished
b dui xiang zong he shi :5050
程序中兩處使用Integer類的對(duì)象作為監(jiān)視器送悔,兩個(gè)Integer的對(duì)象都是分別new出來的慢显,但是仍然可以實(shí)現(xiàn)兩個(gè)線程的通信,所以從從此也可以判斷出Integer內(nèi)部是使用cache的機(jī)制欠啤。