乡下人产国偷v产偷v自拍,国产午夜片在线观看,婷婷成人亚洲综合国产麻豆,久久综合给合久久狠狠狠9

  • <output id="e9wm2"></output>
    <s id="e9wm2"><nobr id="e9wm2"><ins id="e9wm2"></ins></nobr></s>

    • 分享

      String、StringBuffer、StringBuilder源碼解析

       印度阿三17 2019-08-17

      String,StringBuffer與 StringBuilder的區(qū)別?

      String類:

      1. 引用型數(shù)據(jù)類型
      2. 存儲在常量池中

      StringBuilder類:

      1. 線程不安全,適合單線程中使用
      2. 具有數(shù)據(jù)緩存區(qū)
      3. 實現(xiàn)了java.io.Serializable接口,可序列化

      StringBuffer類:

      1. 線程安全,適合多線程中使用
      2. 具有數(shù)據(jù)緩存區(qū)
      3. 實現(xiàn)了java.io.Serializable接口,可序列化
      /*
          final修飾,不能被繼承,不可修改
          
          java.io.Serializable:序列化接口僅用于標識序列化。
          					  序列化:對象轉(zhuǎn)換成字節(jié)流的一個過程,用來處理對象流的機制。
          					  
          Comparable<String>:接口用于對兩個實例化對象比較大小。
          
          CharSequence:只讀的字符序列;
          			抽象方法length(), charAt(int index), subSequence(int start, int end)
          			public String toString();
      */
      
      public final class String 
      implements java.io.Serializable, Comparable<String>, CharSequence {
      
      	public int hashCode() {
              int h = hash;
              if (h == 0 && value.length > 0) {
                  hash = h = isLatin1() ? StringLatin1.hashCode(value)
                                        : StringUTF16.hashCode(value);
              }
              return h;
          }
          
          public boolean equals(Object anObject) {
              if (this == anObject) {
                  return true;
              }
              if (anObject instanceof String) {
                  String aString = (String)anObject;
                  if (coder() == aString.coder()) {
                      return isLatin1() ? StringLatin1.equals(value, aString.value)
                                        : StringUTF16.equals(value, aString.value);
                  }
              }
              return false;
          }
      }
      
      
      final class StringLatin1 {
          public static boolean equals(byte[] value, byte[] other) {
              if (value.length == other.length) {
                  for (int i = 0; i < value.length; i  ) {
                      if (value[i] != other[i]) {
                          return false;
                      }
                  }
                  return true;
              }
              return false;
          }
          
          public static int hashCode(byte[] value) {
              int h = 0;
              int length = value.length >> 1;
              for (int i = 0; i < length; i  ) {
                  h = 31 * h   getChar(value, i);
              }
              return h;
          }
      }
      
      	
      final class StringUTF16 {
          public static int hashCode(byte[] value) {
              int h = 0;
              int length = value.length >> 1;
              for (int i = 0; i < length; i  ) {
                  h = 31 * h   getChar(value, i);
              }
              return h;
          }
          
          @HotSpotIntrinsicCandidate
          public static boolean equals(byte[] value, byte[] other) {
              if (value.length == other.length) {
                  int len = value.length >> 1;
                  for (int i = 0; i < len; i  ) {
                      if (getChar(value, i) != getChar(other, i)) {
                          return false;
                      }
                  }
                  return true;
              }
              return false;
          }
      }
      

      StringBuilder類源碼

      特點:

      1. 線程不安全,適合單線程中使用
      2. 具有數(shù)據(jù)緩存區(qū)
      3. 實現(xiàn)了java.io.Serializable接口,可序列化
      public final class StringBuilder extends AbstractStringBuilder
      implements java.io.Serializable, CharSequence{
          static final long serialVersionUID = 4383685877147921099L;
          
          @HotSpotIntrinsicCandidate
          public StringBuilder() {
              super(16);
          }
          
          @HotSpotIntrinsicCandidate
          public StringBuilder(int capacity) {
              super(capacity);
          }
          
          @HotSpotIntrinsicCandidate
          public StringBuilder(String str) {
              super(str.length()   16);
              append(str);
          }
          
          public StringBuilder(CharSequence seq) {
              this(seq.length()   16);
              append(seq);
          }
          
          
          //個append 方法
          public StringBuilder append(String str) {
              super.append(str);
              return this;
          }
          
          public StringBuilder append(StringBuffer sb) {
              super.append(sb);
              return this;
          }
      }
      
      //抽線類,這個抽象類值得好好看看
      abstract class AbstractStringBuilder implements Appendable, CharSequence {
      
          byte[] value;//The value is used for character storage.
          
          byte coder;//The id of the encoding used to encode the bytes in {@code value}.
      	
          int count;//The count is the number of characters used.
      
      	
      	public AbstractStringBuilder append(String str) {
              if (str == null) {
                  return appendNull();
              }
              int len = str.length();
              ensureCapacityInternal(count   len);
              putStringAt(count, str);
              count  = len;
              return this;
          }
          
          private AbstractStringBuilder appendNull() {
              ensureCapacityInternal(count   4);
              int count = this.count;
              byte[] val = this.value;
              if (isLatin1()) {
                  val[count  ] = 'n';
                  val[count  ] = 'u';
                  val[count  ] = 'l';
                  val[count  ] = 'l';
              } else {
                  count = StringUTF16.putCharsAt(val, count, 'n', 'u', 'l', 'l');
              }
              this.count = count;
              return this;
          }
          
          private void ensureCapacityInternal(int minimumCapacity) {
      		//移位運算符;<<(左移)、>>(帶符號右移)、>>>(無符號右移)
              int oldCapacity = value.length >> coder;
              if (minimumCapacity - oldCapacity > 0) {
              value = Arrays.copyOf(value,newCapacity(minimumCapacity) << coder);
              }
          }
          
         private int newCapacity(int minCapacity) {
              int oldCapacity = value.length >> coder;
              int newCapacity = (oldCapacity << 1)   2;
              if (newCapacity - minCapacity < 0) {
                  newCapacity = minCapacity;
              }
              int SAFE_BOUND = MAX_ARRAY_SIZE >> coder;
              return (newCapacity <= 0 || SAFE_BOUND - newCapacity < 0)
                  ? hugeCapacity(minCapacity): newCapacity;
          }
          
          private final void putStringAt(int index, String str) {
              if (getCoder() != str.coder()) {
                  inflate();
              }
              str.getBytes(value, index, coder);
          }
      }
      
      

      StringBuffer類

      特點:

      1. 線程安全,適合多線程中使用
      2. 具有數(shù)據(jù)緩存區(qū)
      3. 實現(xiàn)了java.io.Serializable接口,可序列化

      transient:不希望在網(wǎng)絡(luò)操作(主要涉及到序列化操作,本地序列化緩存也適用)中被傳輸,這些信息對應(yīng)的變量就可以加上transient關(guān)鍵字。換句話說,這個字段的生命周期僅存于調(diào)用者的內(nèi)存中而不會寫到磁盤里持久化。

       public final class StringBuffer
          extends AbstractStringBuilder
          implements java.io.Serializable, CharSequence
      {
      	private transient String toStringCache;
      	@Override
          public synchronized int length() {
              return count;
          }
      
          @Override
          public synchronized int capacity() {
              return super.capacity();
          }
      
      
          @Override
          public synchronized void ensureCapacity(int minimumCapacity) {
              super.ensureCapacity(minimumCapacity);
          }
          
             @Override
          public synchronized StringBuffer append(Object obj) {
              toStringCache = null;
              super.append(String.valueOf(obj));
              return this;
          }
      
          @Override
          @HotSpotIntrinsicCandidate
          public synchronized StringBuffer append(String str) {
              toStringCache = null;
              super.append(str);
              return this;
          }
          
      	@Override
          @HotSpotIntrinsicCandidate
          public synchronized StringBuffer append(String str) {
              toStringCache = null;
              super.append(str);
              return this;
          }
      
      }
      

      源碼查看
      一個小的面試題
      測試代碼

      import org.junit.Test;
      import java.util.concurrent.CountDownLatch;
      
      public class StringDiff {
          @Test
          public void testStr() {
              String str = "Hello";
      
              long start = System.currentTimeMillis();
              for (int i = 0; i < 1000000; i  ) {
                  str ="1";
                  //str=str.concat("1");
              }
              long end = System.currentTimeMillis();
              System.out.println(end - start);
      
          }
      
          /* 被synchronized修飾*/
          @Test
          //線程安全
          public void testStrBuilder() {
              StringBuilder str = new StringBuilder("Hello");
              long start = System.currentTimeMillis();
              for (int i = 0; i < 10000000; i  ) {
                  str.append("BoGe");
              }
              long end = System.currentTimeMillis();
              System.out.println("StringBuilder測試:" (end - start));
          }
      
          @Test
          //線程不安全
          public void testStrBuffer() {
              StringBuffer str = new StringBuffer("Hello");
      
              long start = System.currentTimeMillis();
              for (int i = 0; i < 10000000; i  ) {
                  str.append("BoGe");
              }
              long end =System.currentTimeMillis();
              System.out.println("StringBuffer測試:" (end-start));
          }
      
          /**CountDownLatch原理:
           *  CountDownLatch是通過一個計數(shù)器來實現(xiàn)的,計數(shù)器的初始化值為線程的數(shù)量。每當一個線程完成了自己的任務(wù)后,計數(shù)器的值就相應(yīng)得減1。
           *  當計數(shù)器到達0時,表示所有的線程都已完成任務(wù),然后在閉鎖上等待的線程就可以恢復(fù)執(zhí)行任務(wù)。
           */
      
          @SuppressWarnings("all")
          @Test
          public void testStringBuilderAndStringBuffer() {
      
              CountDownLatch latch1 = new CountDownLatch(1000);
              CountDownLatch latch2 = new CountDownLatch(1000);
              StringBuffer stringBuffer = new StringBuffer();
              StringBuilder stringBuilder = new StringBuilder();
              for(int i=0;i<1000;i  ){
                  new Thread(new Runnable() {
                      @Override
                      public void run() {
                          try {
                              stringBuilder.append(1);
                          } catch (Exception e) {
                              e.printStackTrace();
                          } finally {
                              latch1.countDown();
                          }
                      }
                  }).start();
              }
              for(int i=0;i<1000;i  ){
                  new Thread(new Runnable() {
                      @Override
                      public void run() {
                          try {
                              stringBuffer.append(1);
                          } catch (Exception e) {
                              e.printStackTrace();
                          } finally {
                              // 遞減計數(shù)器的計數(shù),如果計數(shù)到達零,則釋放所有等待的線程。
                              latch2.countDown();
                          }
                      }
                  }).start();
              }
              
              try {
                  latch1.await();
                  System.out.println(stringBuilder.length());
                  latch2.await();
                  System.out.println(stringBuffer.length());
              } catch (InterruptedException e) {
                  e.printStackTrace();
              }
          }
      }
      
      來源:https://www./content-1-395551.html

        本站是提供個人知識管理的網(wǎng)絡(luò)存儲空間,所有內(nèi)容均由用戶發(fā)布,不代表本站觀點。請注意甄別內(nèi)容中的聯(lián)系方式、誘導(dǎo)購買等信息,謹防詐騙。如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請點擊一鍵舉報。
        轉(zhuǎn)藏 分享 獻花(0

        0條評論

        發(fā)表

        請遵守用戶 評論公約

        類似文章 更多