面试题答案
一键面试可能出现的线程安全问题
- 数据竞争:多个协程同时读写MutableList,可能导致数据不一致。例如,一个协程正在向列表中添加元素,另一个协程同时尝试读取列表,可能会读到不完整或错误的数据。
- 并发修改异常:当一个协程在遍历MutableList时,另一个协程对其进行修改,可能会抛出
ConcurrentModificationException
。
解决方案
- 使用锁机制
import kotlinx.coroutines.* import java.util.concurrent.locks.ReentrantLock val lock = ReentrantLock() val sharedList = mutableListOf<Int>() fun main() = runBlocking { val jobs = List(10) { launch { lock.lock() try { sharedList.add(it) println("Added $it to the list. Current list: $sharedList") } finally { lock.unlock() } } } jobs.forEach { it.join() } }
- 使用Kotlin的线程安全数据结构 - ConcurrentLinkedDeque
import kotlinx.coroutines.* import java.util.concurrent.ConcurrentLinkedDeque val sharedList = ConcurrentLinkedDeque<Int>() fun main() = runBlocking { val jobs = List(10) { launch { sharedList.add(it) println("Added $it to the list. Current list: $sharedList") } } jobs.forEach { it.join() } }
- 使用Kotlin的线程安全数据结构 - Collections.synchronizedList
import kotlinx.coroutines.* import java.util.* val sharedList = Collections.synchronizedList(mutableListOf<Int>()) fun main() = runBlocking { val jobs = List(10) { launch { sharedList.add(it) println("Added $it to the list. Current list: $sharedList") } } jobs.forEach { it.join() } }