1
我有兩個線程通過這個相同的類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;
....
這有幫助,但我仍然有問題,該對象不反應的X和Y的限制。它不會反彈它,它只會反彈初始化的x和y限制 –
我現在知道它爲什麼會打印出初始值和新值,因爲我有兩個BouncingObject線程,但我不明白爲什麼時我運行這個BouncingObject時,它的邊界改變時不會反應。 –
如果您決定將限制設置爲靜態,則所有彈跳對象將共享相同的限制。由於你的「靜態」,每個對象都有自己的限制副本。將它們改爲「靜態」,你的困惑就會消失 - 但你必須改變你的鎖定機制。 – OldCurmudgeon