参考网址:https://www.cnblogs.com/joy99/p/15805916.html
怎么保证同一个变量,在不同线程中,保持它的可见性和原子性?
只用Volatile,打印出来的count并不是100000;然后用如下几种方式,能解决:
1、用AtomicInteger和incrementAndGet()
2、用synchronized
val obj = Any();
synchronized(obj){
count++
}
3、ReentrantLock,
val mLock = ReentrantLock()
mLock.lock()
try {
count++
}finally {
mLock.unlock()
}
4、协程中的Mutex,类似ReentrantLock,
val mutex = Mutex()
mutex.withLock {
count++
}
示例代码:
class TestClass{
// @Volatile
// var count = 0
// var count = AtomicInteger()
// val obj = Any()
// val mLock = ReentrantLock()
val mutex = Mutex()
var count = 0;
suspend fun test() = withContext(Dispatchers.IO) {
repeat(100) {
launch {
repeat(1000) {
// count++
// count.incrementAndGet()
// synchronized(obj){
// count++
// }
// mLock.lock()
// try {
// count++
// }finally {
// mLock.unlock()
// }
mutex.withLock {
count++
}
}
}
}
launch {
delay(3000)
println("end count: $count")
}
}
}
fun main(argv: Array<String>){
println("==== main start ====")
runBlocking {
TestClass().test()
}
println("==== main end ====")
}
打印结果如下:
image.png
网友评论