2017-07-29 33 views
1

我无法理解下面的代码。我的主要问题是为什么使用在线程中分配给“表”数组的值来更新“a”数组。为了更具体一点,我想解释为什么“a”数组不能打印最初的元素(0,1,2,3 ...)。线程的阵列更新

的主要方法的代码和线程:

public class ThreadParSqrt 
{ 
    public static void main(String[] args) 
    { 
     double[] a = new double[1000]; 

     for (int i = 0; i < 1000; i++) 
      a[i] = i; 

     SqrtThread threads[] = new SqrtThread[1000]; 

     for (int i = 0; i < 1000; i++) 
     { 
      threads[i] = new SqrtThread(a,i); 
      threads[i].start(); 
     } 

     for (int i = 0; i < 1000; i++) 
     { 
      try { 
       threads[i].join(); 
      } catch (InterruptedException e) { 
       e.printStackTrace(); 
      } 
     } 

     for (int i = 0; i < 1000; i++) 
     { 
      System.out.println(a[i]); 
     } 
    } 
} 


public class SqrtThread extends Thread 
{ 
    private double [] table; 
    private int index; 

    public SqrtThread(double [] array, int ind) 
    { 
     table = array; 
     index = ind; 
    } 

    public void run() 
    { 
     table[index] = Math.sqrt(table[index]); 
    } 
} 

回答

1

由于a被传递到的SqrtThread构造通过参考(搜索通过引用传递/传值) 。在该构造函数中,现在称为array的引用被存储在私有成员table中。但因为它是一个参考,所以对table的任何更改也将在a(因为这两个引用都指向内存中的相同数组)的更改。

我也许也应该提醒你关于线程安全等等,但是好像你还在学习基础知识。一旦你抓住这些,你可能想要读取线程同步,锁定,事件等。