1.两个线程交替打印 (kotlin)
使用wait() notifyAll(), 注意要wait的线程先start。
fun testThread() {
val lock = Object()
val max = 10
var count = 0
thread(true) {
synchronized(lock) {
while (count < max) {
lock.wait()
println("2")
count++
lock.notifyAll()
}
}
}
thread(true) {
synchronized(lock) {
while (count < max) {
println("1")
count++
lock.notifyAll()
lock.wait()
}
}
}
}