1. 程式人生 > >java中StringBuilder為單線程做的,StringBuffer相反

java中StringBuilder為單線程做的,StringBuffer相反

stringbu [] run lee 沒有 auth stub b- ati

//沒有sycronized修飾method,是線程不安全的,--StringBuffer來彌補這個缺點,但速度就慢了

並沒有測試出來::

技術分享
 1 /**
 2  * 
 3  */
 4 package com.breaver.test.string;
 5 
 6 /**
 7  * @author zzf
 8  [email protected] 2017年6月22日 下午11:09:36
 9  */
10 public class TestStringBuilder implements Runnable{
11     public static StringBuilder strs=new
StringBuilder("my-str:"); 12 private String str; 13 /** 14 * @param args 15 */ 16 17 public static void main(String[] args) { 18 // TODO Auto-generated method stub 19 // TestStringBuilder.test(); 20 new Thread(new TestStringBuilder("123")).start(); 21 new
Thread(new TestStringBuilder("abc")).start(); 22 } 23 public TestStringBuilder(String a) { 24 super(); 25 // TODO Auto-generated constructor stub 26 str=a; 27 } 28 @Override 29 public void run() { 30 // TODO Auto-generated method stub 31 try{ 32
while(true){ 33 System.out.println(strs.toString()); 34 Thread.sleep(1000); 35 strs.append(str); 36 } 37 }catch (Exception e) { 38 // TODO: handle exception 39 e.printStackTrace(); 40 } 41 } 42 public static void test(){ 43 StringBuilder builder =new StringBuilder(); 44 System.out.println(builder.toString()+":"+builder.capacity()); 45 builder.append("123"); 46 System.out.println(builder.toString()+":"+builder.capacity()); 47 builder.append("asssssssssssssqwqw123"); 48 System.out.println(builder.toString()+":"+builder.capacity() 49 +"::fact-size:"+builder.length()); 50 builder.append("Aasssssssssssssqwqw123"); 51 System.out.println(builder.toString()+":"+builder.capacity() 52 +"::fact-size:"+builder.length()); 53 } 54 }
View Code

java中StringBuilder為單線程做的,StringBuffer相反