gpt4 book ai didi

java - 如何在 Java 中防止这种简单的死锁?

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:24:30 26 4
gpt4 key购买 nike

<分区>

我有一个简单的例子来说明如何导致死锁:

class Player {
private String name;

public Player(String name) {
super();
this.name = name;
}

public synchronized void passTo(Player p) {
System.out.println(this.name + " passes to " + p.name);
// to imitate long task
for (int i = 0; i < 1000000000; i++)
;
p.passBack(this);
}

private synchronized void passBack(Player p) {
System.out.println(this.name + " passes back to " + p.name);
}
}

public class Deadlock {

public static void main(String[] args) {
final Player ivan = new Player("Ivan");
final Player petro = new Player("Petro");

new Thread(new Runnable() {
public void run() {
ivan.passTo(petro);
}
}).start();
new Thread(new Runnable() {
public void run() {
petro.passTo(ivan);
}
}).start();
}
}

当我运行这个程序时它会导致死锁。

有哪些可能的解决方案可以防止这种简单的死锁?

谢谢!

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com