I am searching for a way to resolve a deadlock. Take a look at this sample kotlin code which shows a simple dead lock:
data class Human(val name:String) {
@Synchronized fun sayHi(to: Human){
println("$name saying hi to ${to.name}")
Thread.sleep(500)
to.sayHiBack(this)
}
@Synchronized fun sayHiBack(to: Human){
println("$name saying hi back to ${to.name}")
}
}
fun main() {
val adam = Human("adam")
val eve = Human("eve")
val adamThread = Thread {
adam.sayHi(eve)
}.apply {
start()
}
val eveThread = Thread {
eve.sayHi(adam)
}.apply {
start()
}
adamThread.join()
eveThread.join()
}
因此,亚当试图向夏娃打招呼,而夏娃线程正试图向亚当打招呼,所以他们陷入僵局,彼此等待。
因此,为了解决死锁,我们通常会更改资源访问的顺序。
所以我当时想让主函数看起来像这样:
fun main() {
val adam = Human("adam")
val eve = Human("eve")
val adamThread = Thread {
adam.sayHi(eve)
}.apply {
start()
}
adamThread.join() . //wait until adam thread finishes
val eveThread = Thread {
eve.sayHi(adam)
}.apply {
start()
}
eveThread.join()
}
,以便仅在另一个线程完全完成(加入)之后才调用一个线程。但这会减慢速度吧?最好的方法是什么?