gpt4 book ai didi

java - 该 Java 程序没有显示预期的死锁

转载 作者:行者123 更新时间:2023-12-02 11:51:53 26 4
gpt4 key购买 nike

按照 Oracle java 文档 ( https://docs.oracle.com/javase/tutorial/essential/concurrency/deadlock.html ) 中给出的死锁示例,我想模拟我所在国家/地区的情况。当两列火车相向行驶时,到达中间站的火车首先将一把“ key ”交给候车人员(火车不 parking ,但火车司机将装有 key 的大袋子扔到站台上)。在那里等候的工作人员会来收集)。然后由稍后到达中间站的另一列火车收集。如果两列火车同时到达车站,就会导致僵局。因此,我编写了以下代码来说明这一点:

public class Deadlock
{
static class Express
{
private final String name;
public Express(String name)
{
this.name = name;
}
public String getName()
{
return this.name;
}
public synchronized void reached(Express laterTrain)
{
System.out.println(this.name + " is earlier than " +
laterTrain.getName());
giveKey(laterTrain);
}
public synchronized void giveKey(Express laterTrain)
{
System.out.println(name + " gives key to " +
laterTrain.getName());
}
}
public static void main(String[] args)
{
final Express Rajdhani1 = new Express("Rajdhani ONE");
final Express Rajdhani2 = new Express("Rajdhani TWO");
new Thread(new Runnable()
{
public void run()
{
Rajdhani1.reached(Rajdhani2);
}
}).start();
new Thread(new Runnable()
{
public void run()
{
Rajdhani2.reached(Rajdhani1);
}
}).start();
}
}

我期待这样的输出:

Rajdhani ONE is earlier than Rajdhani TWO
Rajdhani TWO is earlier than Rajdhani ONE

并且程序永远卡在那里。但是,我得到了以下输出,并且执行立即返回到命令行。怎么办?

Rajdhani ONE is earlier than Rajdhani TWO
Rajdhani TWO is earlier than Rajdhani ONE
Rajdhani ONE gives key to Rajdhani TWO
Rajdhani TWO gives key to Rajdhani ONE

最佳答案

我没有运行您的代码,但您所做的事情与链接的示例代码不同:您正在调用 giveKey reached() 中的错误对象功能。

根据引用的示例,它应该是:

// bower.bowBack(this);
laterTrain.giveKey(this);

但你正在打电话:

// this.bowBack(bower);
this.giveKey(laterTrain);

关于java - 该 Java 程序没有显示预期的死锁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47830417/

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