標籤:技術分享 run ted 2017年 date ring blog 安全 cep
//沒有sycronized修飾method,是線程不安全的,--StringBuffer來彌補這個缺點,但速度就慢了
並沒有測試出來::
1 /** 2 * 3 */ 4 package com.breaver.test.string; 5 6 /** 7 * @author zzf 8 *@date 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 args15 */16 17 public static void main(String[] args) {18 // TODO Auto-generated method stub19 // 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 stub26 str=a;27 }28 @Override29 public void run() {30 // TODO Auto-generated method stub31 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 exception39 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相反