ReentrantLock锁并发环境线程安全读写ArrayList,Kotlin
import kotlinx.coroutines.*
import java.util.concurrent.locks.ReentrantLock
import kotlin.collections.ArrayList
/**
* 假设这样一种场景:在多线程的并发环境中,不同的线程/协程对于一个线程不安全的列表读写,确保数据写入后,被读取出来是正确无误的。
*
*/
fun main() {
val lock = ReentrantLock()
var list = ArrayList<String>()
runBlocking {
CoroutineScope(Dispatchers.IO).launch {
while (true) {
delay((Math.random() * 10 + 100).toLong())
lock.lock()
println("R--->${list[list.size - 1]}") //这里很容易发生数组越界问题。
lock.unlock()
}
}
while (true) {
val l = ArrayList<String>()
for (i in 0..<(Math.random() * 10 + 10).toInt()) {
l.add("$i")
}
lock.lock()
list.clear()
list.addAll(l)
println("W-${list.size}")
lock.unlock()
delay((Math.random() * 10).toLong())
}
}
}
W-14
W-10
W-11
W-10
W-15
W-14
W-14
W-10
W-14
W-14
R--->13
W-11
W-15
W-14
W-10
W-12
W-11
W-12
R--->11
W-16
W-19
W-11
W-16
W-14
W-16
W-10
R--->9
W-12
W-17
W-11
W-16
W-10
W-19
W-16
W-16
W-14
W-12
R--->11
W-12
W-13
W-16
W-14
W-17
W-15
W-13
R--->12