關于Integer類思考

測試代碼:

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));
    }
}

輸出結果:

i1 == i2? true
i3 == i4? false

為什么都是Integer類的對象會輸出不同的結果呢?
是因為Integer類的內部做了緩存處理,在Integer內部有一個IntegerCache的靜態內部類,該內部類中會緩存-128到127的整數。當用一個int類型的變量給Integer時,會使用自動裝箱的程序。

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++);
      ...
  }
  ...
  //自動裝箱的程序
  public static Integer valueOf(int i) {
    if(i >= IntegerCache.low && i <= IntegerCache.high)
      return IntegerCache.cache[i+(-IntegerCache.low)];
    return new Integer(i);
  }
  ...
}

為了進一步深入地理解Integer中的玄機,可以增加一下難度,使用synchronized關鍵字進一步驗證。

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");
        }
    }
}

輸出結果

deng dui xiang b wan cheng b wan cheng ....
computing is finished
b dui xiang zong he shi :5050

程序中兩處使用Integer類的對象作為監視器,兩個Integer的對象都是分別new出來的,但是仍然可以實現兩個線程的通信,所以從從此也可以判斷出Integer內部是使用cache的機制。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • 1. Java基礎部分 基礎部分的順序:基本語法,類相關的語法,內部類的語法,繼承相關的語法,異常的語法,線程的語...
    子非魚_t_閱讀 31,767評論 18 399
  • 轉自:http://blog.csdn.net/jackfrued/article/details/4492194...
    王帥199207閱讀 8,618評論 3 93
  • Java8張圖 11、字符串不變性 12、equals()方法、hashCode()方法的區別 13、...
    Miley_MOJIE閱讀 3,731評論 0 11
  • 已經沒有音信幾個月了,終于鼓起勇氣問了她的近況,對啊?她挺好的,我應該開心才對。可是為什么開心不起來呢? 看文章說...
    Ttss玄閱讀 266評論 0 1
  • 他叫凡哥,4 年前被他老婆踹了,因為窮。 凡哥和老婆是大學認識的。 他老婆是大學霸,長得還特別漂亮。 凡哥是超級學...
    先森豬閱讀 423評論 0 0