【Java】StringBuilder与StringBuffer

StringBuilder

package com.keytech.task;

import java.util.concurrent.CountDownLatch;

import java.util.concurrent.ExecutorService;

import java.util.concurrent.Executors;

import java.util.concurrent.Semaphore;

//线程不安全

public class StringExample1 {

public static Integer clientTotal=5000;

public static Integer threadTotal=200;

public static StringBuilder stringBuilder=new StringBuilder();

public static void main(String[] args) throws Exception{

ExecutorService executorService = Executors.newCachedThreadPool();

final Semaphore semaphore=new Semaphore(threadTotal);

final CountDownLatch countDownLatch=new CountDownLatch(clientTotal);

for (int i = 0; i < clientTotal; i++) {

executorService.execute(()->{

try{

semaphore.acquire();

update();

semaphore.release();

}catch (Exception e){

e.printStackTrace();

}

countDownLatch.countDown();

});

}

countDownLatch.await();

executorService.shutdown();

System.out.println("size"+stringBuilder.length());

}

private static void update() {

stringBuilder.append("1");

}

}

//size:4999

StringBuffer

package com.keytech.task;

import java.util.concurrent.CountDownLatch;

import java.util.concurrent.ExecutorService;

import java.util.concurrent.Executors;

import java.util.concurrent.Semaphore;

//线程安全

public class StringExample2 {

public static Integer clientTotal=5000;

public static Integer threadTotal=200;

public static StringBuffer stringBuffer=new StringBuffer();

public static void main(String[] args) throws Exception{

ExecutorService executorService = Executors.newCachedThreadPool();

final Semaphore semaphore=new Semaphore(threadTotal);

final CountDownLatch countDownLatch=new CountDownLatch(threadTotal);

for (int i = 0; i < clientTotal; i++) {

executorService.execute(()->{

try{

semaphore.acquire();

update();

semaphore.release();

}catch (Exception e){

e.printStackTrace();

}

countDownLatch.countDown();

});

}

countDownLatch.await();

executorService.shutdown();

System.out.println("size:"+stringBuffer.length());

}

private static void update() {

stringBuffer.append("1");

}

}

//size:5000

StringBuffer使用synchronized保证线程安全

 @Override

public synchronized StringBuffer append(String str) {

toStringCache = null;

super.append(str);

return this;

}

总结

关注微信公众号:【入门小站】,解锁更多知识

【Java】StringBuilder与StringBuffer

以上是 【Java】StringBuilder与StringBuffer 的全部内容, 来源链接: utcz.com/a/94875.html

回到顶部