1

简单来说,我的问题如下:

我有一个名为Test的类,它有3个双数组,分别命名为array1、array2、array3(假设它们的长度相同)。它有一个名为Estep的主要函数,我需要用多线程来实现这个函数来改进速度。

在Estep中,我需要修改array1和array2,而array3仅供读取。我定义了一个名为which_array的指示变量来指示要修改哪个数组。我将三个数组传递给Estep并修改array1和array2。

我的代码如下,我对其进行了测试,它工作正常,因为 Estep 中 array1 和 array2 的修改可以在 Test 类中看到。但我仍然怀疑它是否绝对正确。我想知道是否应该将volatile添加到 Test 类中的三个 array1 中,还是需要一些同步机制?

任何意见,将不胜感激!

public class Test{

    double[] array1;
    double[] array2;
    double[] array3;
    //for simplifization, I omitted the code for allocation and initialization of the the arrays.
    public void EstepInTest()
    {
        final CountDownLatch countdown = new CountDownLatch(2);

    Estep modifyArray1 = new Estep(array1, array2, array3, 1,countdown);
    Thread t1 = new Thread( firstHalf);
    t1.start();

    Estep modifyArray2 = new Estep(array1, array2, array3, 2,countdown);    
        Thread t2 = new Thread(secondHalf);
    t2.start();

    try{
    countdown.await();
    }catch (InterruptedException e) {
        e.printStackTrace();
    }

        //do next things
    }

}

class Estep implements Runnable{

    double[] array1;
    double[] array2;
    double[] array3;
    int which_array;

    Estep(double[] array1, double[] array2, double[] array3, int which_array, CountDownLatch cd)
    {
        this.array1 = array1;
        this.array2 = array2;
        this.array3 = array3;
        this.which_array = which_array;
        this.cd = cd;
    }

    public void run(){

        if( this.which_array == 1){
           for( int i = 0; i < array1.length; ++i )
           {   
               array1[i] = array1[i] + array3[i];
           }  
        }else{
           for( int i = 0; i < array2.length; ++i )
           {   
               array2[i] = array2[i] + array3[i];
           }
        }
        cd.countDown();
   }
4

3 回答 3

2

这是正确的。CountDownLatch.await()保证在它返回之前完成的所有事情都发生在它返回之后完成的所有事情之前。

如果您只是将要修改的数组传递给 Estep 构造函数,而不是传递两个数组和一个指示要修改哪一个的幻数,那么您的代码会更简洁、更短。

编辑:

关于对 的访问array3,它也是安全的,因为正如并发包的文档中start所解释的那样,对线程的调用发生在启动线程中的任何操作之前。array3因此,这两个线程将在启动它们之前看到对其所做的所有修改。

另外,请注意,使数组易失性只会使数组引用易失性。它不会使其元素不稳定。

于 2013-07-21T13:39:18.670 回答
0

考虑只向 Estep 传递两个数组,一个用于修改,下一个用于读取。在这种情况下,您不需要多余的 which-array 变量和运行中的通用代码

于 2013-07-21T13:47:48.537 回答
0

我对倒计时闩锁不太熟悉。

您还可以同步数组对象本身。您可以通过将数组设置为要在 getter 和 setter 中同步的监视器对象来做到这一点。这应该防止对影响您当前行的数组的任何访问,并将阻止以异步方式发生的最少代码量。

// In the original test class
public int getArray1(int index) {

   unsynchronized_statements...

   int result;
   synchronized(array1) {
       result = array1[index]...
   }
   return result;
}
于 2013-07-21T13:52:11.543 回答