线程读者和作者的合作

时间:2013-04-13 12:50:41

标签: java multithreading paint

我有一个课(我会用非常简单的方式)

当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();
         }
   }
}

1 个答案:

答案 0 :(得分:0)

实现此目的的最简单方法是在movedraw方法中添加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
    }     
}