gpt4 book ai didi

java - 跨对象实例同步

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

我有一个转子对象,它有一个 goalSpeed 和一个 currentSpeed。每个人都尝试改变其当前速度以匹配设置的目标速度。我有 4 个这样的转子,运行 4 个独立的线程。 Controller 定期为每个目标分配一个新的 goalSpeed。

当我尝试在每个转子中更改其当前速度时,我永远不能超过所有转子当前速度的总和以超过 X 值。 sum(currentSpeed(Rotor1) + ... + currentSpeed(Rotor2)) !> X.

这是我的问题:当我检查是否可以增加转子的当前速度时,我对速度总和条件做了一个 if 语句。然而,在检查之后,由于每个转子都是一个单独的线程,因此另一个转子可能会更改其值。因此我在另一个线程中的检查不再有效。如何确保当我使用一个转子的 setNewSpeed() 方法时,其他转子不会改变其当前速度?

class Rotor implements Runnable {
private int id;
private int goalSpeed;
private int currentSpeed;
private Controller controller;
private int Y;
private int failedAttempts;
private int successAttempts;
private int maxSpeed;

public int getSuccessAttempts() {
return successAttempts;
}

public void setSuccessAttempts(int successAttempts) {
this.successAttempts = successAttempts;
}

public int getMaxSpeed() {
return maxSpeed;
}

public void setMaxSpeed(int maxSpeed) {
this.maxSpeed = maxSpeed;
}

public int getFailedAttempts() {
return failedAttempts;
}

public Rotor(Controller c, int Y, int id){
this.controller = c;
this.Y = Y;
this.id = id;
this.currentSpeed = 0;
this.failedAttempts = 0;
this.goalSpeed = 0;
this.maxSpeed = 0;
this.successAttempts = 0;
}

synchronized public void setGoalSpeed(int s){
this.goalSpeed = s;
}

public int getCurrentSpeed(){
return currentSpeed;
}

synchronized private void setNewSpeed(){
int currentDrain = 0;
for(Rotor r : controller.getRotors()){
currentDrain = currentDrain + r.getCurrentSpeed();
}
if((currentDrain + (goalSpeed - currentSpeed)) > 20){
//we cannot increase by total amount because drain too high
System.out.println("failed");
this.failedAttempts++;
currentSpeed = currentSpeed + (20 - currentDrain);
System.out.println("currentSpeed:" + currentSpeed);
} else {
System.out.println("success");
successAttempts++;
currentSpeed = goalSpeed;
}
// System.out.println("goalSpeed:" + goalSpeed);
// System.out.println("currentDrain:" + currentDrain);

}

public void run() {
try {
while(true){
setNewSpeed();
if(currentSpeed > maxSpeed){
maxSpeed = currentSpeed;
}

Thread.sleep(Y);
}
} catch (InterruptedException e) {
System.out.println("Rotor " + id + ": checks=" + (int)(successAttempts + failedAttempts) + ", success rate=" + successAttempts + ", failedAttempts=" + failedAttempts + ", max=" + maxSpeed);
}
}
}

最佳答案

在所有转子之间共享的锁上进行同步。现在它们每个人都在自己的锁(即 this)上进行同步,因此即使该方法是同步的,它也可以同时在不同的对象上调用。

关于java - 跨对象实例同步,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41881418/

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