java中StringBuilder为单线程做的,StringBuffer相反

Posted 红狗<葬爱>贼公子

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java中StringBuilder为单线程做的,StringBuffer相反相关的知识,希望对你有一定的参考价值。

//没有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 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相反的主要内容,如果未能解决你的问题,请参考以下文章

JAVA常用类_StringBuffer和StringBuilder

Java之StringBuffer和StringBuilder的差别与联系

Java之String+StringBuffer+StringBuilder

Java中StringStringBuilderStringBuffer的区别

StringBuffer StringBuilder线程安全的理解

java StringBuilder 和 StringBuffer