Concurrent Programming in Java 才翻5頁就充滿疑惑的程式碼,大家幫忙分析分析

newjoy發表於2004-11-01
書上說這段程式碼解決了併發問題:但我橫看豎看還是有問題呀:

import java.util.Random;

class Particle{
  protected int x;
  protected int y;
  protected final Random rng = new Random();

  public Particle(int inX,int inY){
    x = inX;
    y = inY;
  }

  public synchronized void move(){
    x += rng.nextInt(10) - 5 ;
    y += rng.nextInt(20) - 10;
  }

  public void draw(Graphics g){
    int lx,ly;
    synchronized (this) {lx=x;ly=y;}
    g.drawRect(lx,ly,10,10);
  }
}
<p class="indent">

1、由於 move() 與 draw(Graphics g) 方法可能會被兩個執行緒同時呼叫,那它還是沒有解決,“當draw操作使用move方法呼叫前的y值和move方法呼叫後的x值繪製一個例子的圖形”。

2、protected final Random rng = new Random(); 為什麼定義為final?好處具體表現在什麼地方?

相關文章