0

我有一堂课(我会以非常简单的方式说)

Window 正在绘制图形,而 Mover 正在更改它们的坐标(x,y),我不想Window在 Mover 移动它时读取图形的坐标。

class Figure{
int x, int y;
Figure(){...}

  void move(int x, int y){ //when mover is moving by this method
      this.x+=x;
      this.y+=y;
  }
  void draw(Graphics g){ //i do not want this method running
      g.draw(x,y); //I USE x,y here
  }     
}

然后我有Mover修改x,y的类Figure

class Mover extends Thread{
  Figure f;
  Mover(Figure f){
  this.f = f;
  }
     public void run(){
         while(true){f.move(3,4);}
         Thread.sleep(30);

//
      }       
    }

最后

class Window extends JFrame(){
ArrayList<Figure> l;
   public void paint(Graphics g){
      while(true){
        foreach
          l.draw();
         }
   }
}
4

1 回答 1

0

完成此操作的最简单方法是将synchronized关键字添加到moveanddraw方法。这将使用 锁定方法this,因此一次只能执行一个(此外,您将不能同时执行move多次)。

class Figure{
    int x, int y;
    Figure(){...}

    public synchronized void move(int x, int y){ //when mover is moving by this method
         this.x+=x;
         this.y+=y;
    }
    public synchronized void draw(Graphics g){ //i do not want this method running
        g.draw(x,y); //I USE x,y here
    }     
}
于 2013-04-13T13:12:21.690 回答