gpt4 book ai didi

java - 如何在通过循环修改数据时立即从对象访问数据

转载 作者:行者123 更新时间:2023-12-02 11:46:22 25 4
gpt4 key购买 nike

有代码

public class Main {
public static void main(String[] args) throws InterruptedException {

// A running ball
class Ball {
private double x, y, radius, xvel, yvel;
private long timeframe;
private boolean moving;
public Ball(double x, double y, double radius, double xvel, double yvel, long timeframe) throws InterruptedException {
super();
this.x = x;
this.y = y;
this.radius = radius;
this.xvel = xvel;
this.yvel = yvel;
this.timeframe = timeframe;
this.moving = true;
while(moving) {
// The next print line is what i want to run outside of this constructor
System.out.println("x:" + getX() + " " + "y:" + getY());
move();
Thread.sleep(timeframe);
}
}
private void move() {
x += xvel;
y += yvel;
}
public double getX() {
return x;
}
public double getY() {
return y;
}
public void setXvel(double xvel) {
this.xvel = xvel;
}
public void setYvel(double yvel) {
this.yvel = yvel;
}
}

Ball ball = new Ball(0, 0, 1, .5, .5, 1000);
}
}

现在我想访问球的 x 和 y 字段在跑。我不能在这里做 ball.getX() 因为构造函数内部有一个循环首先完成。我怎样才能在循环运行时执行此操作。有使用线程的想法,但我看不到实现细节..

最佳答案

晚上好,Mac JalLoh,

我认为您正在搜索的是synchronized Java关键字: https://docs.oracle.com/javase/tutorial/essential/concurrency/syncmeth.html以及 Java 7 中引入的 Executor 框架: https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/Executor.html

简而言之,如果您希望球移动,并且外部观察者必须读取轨迹,您可能需要两个不同的线程,这两个线程在访问同一对象时进行同步。事实上,在 Java 中,您无法同时修改球的位置并读取它。为什么 ?因为您永远无法确定职位何时更新。这会导致位置读取和写入的不确定性(在谷歌中查找线程安全)。我们不喜欢不确定性,所以我们放了synchronized关键字(可以说是先到先得)。

此外,我认为将球运动包含在 Ball 构造函数中并不是一个好的做法。事实上,构造函数回答了“什么是球(具有原点和半径的 3D 对象)”的问题,而平移或旋转运动则回答了运动的物理问题。这两个问题需要解关联(您可以引入一个作用于 Ball 实例的外部对象)

关于java - 如何在通过循环修改数据时立即从对象访问数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48175121/

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