该算法遍历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
不是你的问题问,但在查看你的代码时,你同步“this”,这是指你的线程,因此没有实际效果。我猜你的意图是在线程之间进行同步,在这种情况下,您应该在“Jacobi.this”(Jacobi的封闭实例,对于所有创建的线程共有的线程的封闭实例)进行同步。 – 2010-06-03 12:52:28
我实现了你的修正,但我仍然像输出困惑...我必须在create_threads()中使Thread.sleep(300)???使用一个循环后,我开始所有线程和使用线程[ k] .join() – 2010-06-03 15:41:34
仍然得到数组索引超出范围! – 2010-06-03 15:53:21