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;
....
4

1 回答 1

1

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

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

另一种选择是进行限制static,以便对象的所有实例共享它们。

于 2013-03-28T11:52:59.587 回答