2010-06-03 76 views
0

該算法遍歷2D NxN數組,使每個元素成爲其周圍4個鄰居(左,右,上,下)的平均值。實現jacobi算法實現拉普拉斯方程

NxN數組最初全部爲零,並且被1的餘數所包圍,如下面的示例 所示。 1永遠不會改變,0會逐漸增加。

   1 1 1 1 1 1 1 1 
      1 0 0 0 0 0 0 1 
      1 0 0 0 0 0 0 1 
      1 0 0 0 0 0 0 1 
      1 0 0 0 0 0 0 1 
      1 0 0 0 0 0 0 1 
      1 0 0 0 0 0 0 1 
      1 1 1 1 1 1 1 1 

我已經實現了以下代碼,並且正在獲取數組索引超出範圍的異常。請糾正我。

my code : 
     public class Main { 
static int NO_OF_THREADS =8; 

/** 
* @param args the command line arguments 
*/ 
public static void main(String[] args) { 
    // TODO code application logic here 
     Jacobi jacobi = new Jacobi(NO_OF_THREADS); 
     jacobi.initialize(); 
     jacobi.create_threads(); 
    } 

    }//end of Main class 

    public class Jacobi { 
int ROWS=1000,COLS=1000; 
private int i; 
private int upper=100;//prevents buffer overflow 
private int lower=99;//prevents buffer overflow 
private int j; 
private double[][] jacobi=new double[ROWS][COLS]; 
private int NO_OF_THREADS; 


public Jacobi(int k) 
{ 
    NO_OF_THREADS=k; 
} 

public void initialize() { 
     for(i=1;i<=upper;i++) 
      { 
      for(j=1;j<=upper;j++) 
       { 

         if((i==1)||(i==upper)||(j==1)||(j==upper)){ 
         jacobi[i][j]=1.0; 
         } 

        else 
          jacobi[i][j]=0.0; 


       } 

      } 

    } 
       public double[][] getJacobi() 
       { 
        return jacobi; 
       } 

       public void create_threads() 
       { 
        theThread[] threads=new theThread[NO_OF_THREADS]; 
        for(int k=1;k<=NO_OF_THREADS;k++) 
        { 
         threads[k]=new theThread(); 
         threads[k].start(); 
        } 
       } 
       //Inner class of Jacobi 

      class theThread extends Thread { 

       @Override 
       public void run() 
       { 
        for(int q=2;q<=lower;q++) 
        { 

        System.out.println("The ID of this thread is: "+getName()); 
        for(int j=2;j<=lower;j++) 
         { 
         synchronized(Jacobi.this) 
         { 

         jacobi[q][j]=(jacobi[q-1][j]+jacobi[q+1][j]+jacobi[q] [j-1]+jacobi[q][j+1])/4; 
         }//end of synchronized 
       }//end of inner for loop 


      }//end of for loop 
    } 
}//end of theThread class 
}//end of jacobi class 
+0

不是你的問題問,但在查看你的代碼時,你同步「this」,這是指你的線程,因此沒有實際效果。我猜你的意圖是在線程之間進行同步,在這種情況下,您應該在「Jacobi.this」(Jacobi的封閉實例,對於所有創建的線程共有的線程的封閉實例)進行同步。 – 2010-06-03 12:52:28

+0

我實現了你的修正,但我仍然像輸出困惑...我必須在create_threads()中使Thread.sleep(300)???使用一個循環後,我開始所有線程和使用線程[ k] .join() – 2010-06-03 15:41:34

+0

仍然得到數組索引超出範圍! – 2010-06-03 15:53:21

回答

1

在行

int ROWS,COLS=1000; 

我覺得要改變,要

int ROWS=1000, COLS=1000; 

否則ROWS沒有正確設置...

+0

在原始代碼中,「ROWS」將被設置爲「0」而不是「1000」。 – Jesper 2010-06-03 11:42:35

+0

是的,我已經糾正了這兩個錯誤,即設置ROWS = 1000,並在線程之間進行同步(Jacobi.this),但我仍然得到數組索引超出界限。所以我試圖通過試驗和錯誤修復上限和下限,但它仍然無法正常工作。 – 2010-06-03 15:26:41

+0

@SANJAY RAO:請您發佈更新的代碼嗎?你可以修復縮進,否則很難閱讀:) – psmears 2010-06-03 16:07:39