//证明StringBuffer线程安全,StringBuilder线程不安全
StringBuffer stringBuffer = new StringBuffer();
StringBuilder stringBuilder = new StringBuilder();
CountDownLatch latch1 = new CountDownLatch(1000);
CountDownLatch latch2 = new CountDownLatch(1000);
long start = System.currentTimeMillis();
for(int i=0;i<1000;i++){
new Thread(new Runnable() {
@Override
public void run() {
synchronized (stringBuilder){
try {
stringBuilder.append(1);
} catch (Exception e) {
e.printStackTrace();
} finally {
latch1.countDown();
}
}
}
}).start();
}
long end = System.currentTimeMillis();
//System.out.println(end-start);
long start1 = System.currentTimeMillis();
for(int i=0;i<1000;i++){
new Thread(new Runnable() {
@Override
public void run() {
try {
stringBuffer.append(1);
} catch (Exception e) {
e.printStackTrace();
} finally {
latch2.countDown();
}
}
}).start();
}
long endq = System.currentTimeMillis();
//System.out.println(endq-start1);
try {
latch1.await();
System.out.println("stringBuilder : "+stringBuilder.length());
latch2.await();
System.out.println("stringBuffer : "+stringBuffer.length());
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}