验证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();
	}
  }
}

猜你喜欢

转载自blog.csdn.net/weixin_42227576/article/details/88542535
今日推荐