StringBuilder线程不安全效果演示
public static void main(String[] args) throws InterruptedException {
System.out.println("StringBuffer: ");
for (int i = 0; i < 10; i++) {
StringBuffer stringBuffer = new StringBuffer();
Thread thread1 = new Thread(() -> {
for (int j = 0; j < 5000; j++) {
stringBuffer.append("a");
}
});
Thread thread2 = new Thread(() -> {
for (int j = 0; j < 5000; j++) {
stringBuffer.append("b");
}
});
thread1.start();
thread2.start();
thread1.join();
thread2.join();
System.out.println(stringBuffer.length());
}
System.out.println("StringBuilder: ");
for (int i = 0; i < 10; i++) {
StringBuilder stringBuilder = new StringBuilder();
Thread thread1 = new Thread(() -> {
for (int j = 0; j < 5000; j++) {
stringBuilder.append("1");
}
});
Thread thread2 = new Thread(() -> {
for (int j = 0; j < 5000; j++) {
stringBuilder.append("1");
}
});
thread1.start();
thread2.start();
thread1.join();
thread2.join();
System.out.println(stringBuilder.length());
}
}
Output:
StringBuffer:
10000
10000
10000
10000
10000
10000
10000
10000
10000
10000
StringBuilder:
6106
6184
6502
6506
5910
6248
6203
7160
6327
7650
发表评论