我有一个课(我会用非常简单的方式)
当Mover正在改变它们的坐标(x,y)时,窗口正在绘制图形,而当Mover移动它时,我不想Window
读取图形的坐标。
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();
}
}
}
答案 0 :(得分:0)
实现此目的的最简单方法是在move
和draw
方法中添加synchronized关键字。这将使用this
锁定方法,因此一次只能执行一个方法(此外,您将无法同时执行move
多次)。 / p>
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
}
}