我有两个线程通过同一个类BouncingObject运行。 BouncingObject只是从屏幕边界反弹。在某些点上,我想重新定义主线程中的屏幕边界。但由于某种原因,它并没有完全奏效。当我使用alterBounceBoundaries方法改变屏幕边界时,它会改变它们,但不完全。边界值使用方法和初始化值在设定边界之间保持变化。为什么?。正如您所看到的,我在线程运行时打印出限制值,我可以看到orig_x,orig_y,lim_x,lim_y的值在更改的值和初始值之间切换。这些值是bounceobject检测屏幕边界的方式。
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;
....
答案 0 :(得分:1)
如果有两个线程正在运行弹跳对象,则可能有两个对象被弹回。我愿意打赌你只是在改变其中一个的限制。
基本上,当您想要更改限制时,请确保更改所有对象的限制。
另一种选择是设置限制static
,以便它们被对象的所有实例共享。