gpt4 book ai didi

java - 线程变量不断变化

转载 作者:太空宇宙 更新时间:2023-11-04 07:43:28 25 4
gpt4 key购买 nike

我有两个线程通过同一个类 BouncingObject 运行。 BouncingObject 只是不断地弹离屏幕边界。在某些时候,我想在主线程中重新定义这些屏幕边界。但由于某种原因,它不太有效。当我使用 alterBounceBoundaries 方法更改屏幕边界时,它会更改它们,但不会完全更改。边界值在使用该方法设置的边界和初始化值之间不断变化。为什么?。正如您所看到的,我在线程运行时打印出了限制值,并且我可以看到 orig_x、orig_y、lim_x、lim_y 的值在更改值和初始化值之间切换。这些值是反弹对象检测屏幕边界的方式。

class BouncingObject extends D_Object implements Runnable 
{
public int MAX_SPEED = 20;
public int MIN_SPEED = 10;
public volatile double orig_x = 0;
public volatile double orig_y = 0;
public volatile double lim_x = 0;
public volatile double lim_y = 0;
public String rand = "rand";

BouncingObject(String nm,BufferedImage image, int x,int y, int w, int h, int ox, int oy, int spd){
super(nm,image,x,y,w,h,ox,oy,spd);
orig_x = 0;
orig_y = 0;
lim_x = 603;
lim_y = 393;
Thread new_bounce_thread = new Thread(this);
new_bounce_thread.start();
}

//run this code in it's own thread
public void run() {
while(true){
//sleep for a short time to create a slower frame rate
try {Thread.sleep (20); }
catch (InterruptedException e){}
this.bounceObject(orig_x,orig_y,lim_x,lim_y,"rand");
System.out.println("orig_x: "+orig_x);
System.out.println("orig_y: "+orig_y);
System.out.println("lim_x: "+lim_x);
System.out.println("lim_y: "+lim_y);
}
}

public synchronized void alterBounceBoundaries(double origin_x, double origin_y, double limit_x, double limit_y, String rand_o_no){
orig_x = origin_x;
orig_y = origin_y;
lim_x = limit_x;
lim_y = limit_y;
rand = rand_o_no;
System.out.println("Change Boundaries");
}

//used to determine when the bouncingobject has reached a little and needs to bounce
public synchronized void bounceObject(double origin_x, double origin_y, double limit_x, double limit_y, String rand_o_no){
if(obj_x > old_obj_x){
old_obj_x = obj_x;
....

最佳答案

如果您有两个线程运行弹跳对象,则可能有两个对象被弹跳。我敢打赌您只会更改其中一项的限制。

本质上,当您想要更改限制时,请确保更改所有对象的限制。

另一种选择是将限制设为静态,以便对象的所有实例共享它们。

关于java - 线程变量不断变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15680823/

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