多线程通信
使用三个线程按顺序打印 1000 个 str 中的字符
synchorized
fun main() {
val str = "str"
val times = 1000
val threadSize = 3
var cursor = 0
val lock = Object()
val func = fun(currentIndex: Int) {
for (i in 0 until times) {
synchronized(lock) {
while (cursor % threadSize != currentIndex) {
lock.wait()
}
print(str[cursor++ % str.length])
lock.notifyAll()
}
}
}
repeat(threadSize) { currentIndex ->
thread {
func(currentIndex)
}
}
}
lock+condition
fun main() {
val str = "str"
val times = 1000
val threadSize = 3
val lock = ReentrantLock()
val conditions = Array(threadSize) { lock.newCondition() }
var cursor = 0
val func = fun(currentIndex: Int, currentCondition: Condition, nextCondition: Condition) {
for (i in 0 until times) {
lock.lock()
try {
while (cursor % threadSize != currentIndex) {
currentCondition.await()
}
print(str[cursor++ % str.length])
nextCondition.signal()
} finally {
lock.unlock()
}
}
}
repeat(threadSize) { currentIndex ->
thread {
func(currentIndex, conditions[currentIndex], conditions[(currentIndex + 1) % threadSize])
}
}
}