gpt4 book ai didi

Java,使用同步方法的多线程

转载 作者:搜寻专家 更新时间:2023-10-31 19:57:04 24 4
gpt4 key购买 nike

我有时无法让我的程序不死锁。我想我需要添加第三个同步方法 release,它可以用来在调用 ping 后释放另一个线程。代码如下。

// Attempt at a simple handshake.  Girl pings Boy, gets confirmation.
// Then Boy pings girl, get confirmation.
class Monitor {
String name;

public Monitor (String name) { this.name = name; }

public String getName() { return this.name; }

// Girl thread invokes ping, asks Boy to confirm. But Boy invokes ping,
// and asks Girl to confirm. Neither Boy nor Girl can give time to their
// confirm call because they are stuck in ping. Hence the handshake
// cannot be completed.
public synchronized void ping (Monitor p) {
System.out.println(this.name + " (ping): pinging " + p.getName());
p.confirm(this);
System.out.println(this.name + " (ping): got confirmation");
}

public synchronized void confirm (Monitor p) {
System.out.println(this.name+" (confirm): confirm to "+p.getName());
}
}

class Runner extends Thread {
Monitor m1, m2;

public Runner (Monitor m1, Monitor m2) {
this.m1 = m1;
this.m2 = m2;
}

public void run () { m1.ping(m2); }
}

public class DeadLock {
public static void main (String args[]) {
int i=1;
System.out.println("Starting..."+(i++));
Monitor a = new Monitor("Girl");
Monitor b = new Monitor("Boy");
(new Runner(a, b)).start();
(new Runner(b, a)).start();
}
}

最佳答案

当某些操作需要获取两个不同的锁时,确保不存在死锁的唯一方法是确保尝试执行这些操作的每个线程都以相同的顺序获取多个对象上的锁。

要修复死锁,您需要像这样修改代码 - 不漂亮,但它可以工作。

 public void ping (Monitor p) {
Monitor one = this;
Monitor two = p;
// use some criteria to get a consistent order
if (System.identityHashCode(one) > System.identityHashCode(two)) {
//swap
Monitor temp = one;
one = two;
two = one;
}
synchronized(one) {
synchronized(two) {
System.out.println(this.name + " (ping): pinging " + p.getName());
p.confirm(this);
System.out.println(this.name + " (ping): got confirmation");
}
}
}

关于Java,使用同步方法的多线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11526460/

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