驗證Stringbuffer 與StringBuilder的區別:線程安全與非線程安全。

驗證Stringbuffer 與StringBuilder的區別:線程安全與非線程安全。

package prepare;

import java.util.concurrent.CountDownLatch;

import org.junit.Test;

/**
 * 
 * @author zr
 *驗證Stringbuffer 與StringBuilder的區別:線程安全與非線程安全。
 */

public class testStringBuilderAndStringBuffer {
	
 
	StringBuffer stingBuffer = new StringBuffer();
	
	StringBuilder stringBuilder = new StringBuilder();

	CountDownLatch countDownLatch1 = new CountDownLatch(1000);
	
	CountDownLatch countDownLatch2 = new CountDownLatch(1000);
	
    for(int i=0;i<1000;i++){
    	new Thread(new Runnable() {
			
			public void run() {
				// TODO Auto-generated method stub
				try {
					stringBuilder.append(1);
				} catch (Exception e) {
					e.printStackTrace();
				}finally {
					countDownLatch1.countDown();
				}
			}
		}).start();
    }
	
    for(int j=0;j<1000;j++){
    	new Thread(new Runnable() {
			
			public void run() {
				// TODO Auto-generated method stub
				try {
					stingBuffer.append(1);
				} catch (Exception e) {
					e.printStackTrace();
				}finally {
					countDownLatch2.countDown();
				}
			}
		}).start();
    }



	try {
		countDownLatch1.await();
	    System.out.println(stringBuilder.length());
	    countDownLatch2.await();         
	    System.out.println(stingBuffer.length());
	} catch (InterruptedException e) {
	    // TODO Auto-generated catch block
	    e.printStackTrace();
	}
  }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章