用StringBuilder的append方法时,会出现挂掉的情况,是多线程导致的,报错信息如下
AndroidRuntime: FATAL EXCEPTION: Thread-10
AndroidRuntime: Process: com.xxxxx, PID: 4010
AndroidRuntime: java.lang.ArrayIndexOutOfBoundsException: dstBegin > dst.length. dstBegin=294965, dst.length=294910
AndroidRuntime: at java.lang.String.getChars(String.java:802)
AndroidRuntime: at java.lang.AbstractStringBuilder.append(AbstractStringBuilder.java:452)
AndroidRuntime: at java.lang.StringBuilder.append(StringBuilder.java:137)
AndroidRuntime: at com.android.tools.analysis.speedtest.guangdong.ui.FragmentStartReady$onViewCreated$4$1.invoke(FragmentStartReady.kt:130)
AndroidRuntime: at com.android.tools.analysis.speedtest.guangdong.ui.FragmentStartReady$onViewCreated$4$1.invoke(FragmentStartReady.kt:39)
AndroidRuntime: at kotlin.concurrent.ThreadsKt$thread$thread$1.run(Thread.kt:30)
复现代码如下
val sb = StringBuilder()
for (i in 0 until 10) {
thread {
for (i1 in 0 until 10000) {
sb.append("some string")
}
}
}
解决办法是使用StringBuffer
参考java - What actual cause the StringBuilder fails in multi threading environment - Stack Overflow