gpt4 book ai didi

java - 防止 Circles 联盟出现僵局

转载 作者:行者123 更新时间:2023-11-30 04:30:53 25 4
gpt4 key购买 nike

我有一个 CircleImpl 类,它实现了一个只能存在于 XY 正侧的圆(半径>=0、x>=半径和 y>=半径。)

我在 CircleImpl 中有一个函数:

//this function changes the current circle (this) to make it contain the circle other.
public synchronized void union(Circle other) throws Exception {
if (!checkInv(other.getX(),other.getY(),other.getRadius()))
throw new Exception("Illegal circle: " + other);
synchronized (other) {
setRadius(calculateUnionRadius(_x,_y,_radius,other.getX(),other.getY(),other.getRadius()));
}
}

现在这里可能存在死锁的问题:

Circle c1,c2; 

T1: c1.union(c2);
T2: c2.union(c1);

c1 锁定自身(this),并在锁定“其他”(c2)之前,c2 获得 CPU 时间并锁定自身(c2),并尝试锁定“其他”(c1)并进入阻塞模式。

有什么可能的简单解决方案不包括资源排序(System.identityHashCode)?

最佳答案

简单(但不是真正有效)的解决方案是同步共享对象上的union操作,例如在Circle.class上。缺点是它只允许在任何给定时间为 1 个线程执行 Union。像这样的东西:

public void union(Circle other) throws Exception { 
synchronized (Circle.class) {
if (!checkInv(other.getX(),other.getY(),other.getRadius())) {
throw new Exception("Illegal circle: " + other);
}
setRadius(calculateUnionRadius(_x,_y,_radius,other.getX(),other.getY(),other.getRadius()));
}
}

关于java - 防止 Circles 联盟出现僵局,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14675809/

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