2

I have a static Array, arr, whose elements are getting squarred and stored back again using the 'squarring' method. I want two threads to simultaneously modify the array. Each thread works on half of the array.

public class SimplerMultiExample {

    private static int[] arr = new int[10];
    public static void squarring(int start, int end)
    {
        for(int i=start; i<end; i++)
        {
            arr[i]*=arr[i];
            System.out.println("here "+Thread.currentThread().getName());
        }
    }


    private static Runnable doubleRun = new Runnable() {
        @Override
        public void run() {
        if(Integer.parseInt(Thread.currentThread().getName())==1)
            squarring(0,arr.length/2);  //Thread named "1" is operaing on
                                        //the 1st half of the array.
        else
            squarring(arr.length/2,arr.length);
        }
     };

    public static void main(String[] args){

         Thread doubleOne = new Thread(doubleRun);
         doubleOne.setName("1");

         Thread doubleTwo = new Thread(doubleRun);
         doubleTwo.setName("2");

         doubleOne.start();
         doubleTwo.start();
    }
}

The sysout in the 'squarring' method tells me that the threads are going into the method serially, that is, one of threads finishes before the other one accesses it. As a result, one of the threads finishes early whereas the other ones takes considerably longer to complete. I have tested the code with 1 million elements. Please advice on what I can do to ensure that the threads operate in parallel. P.S - I am using a dual core system.

  • There is not enough work for the two threads to overlap meaningfully. Each thread will take a microsecond or so to execute. Try changing the array size from 10 to 1,000,000, and add `join()` calls at the end of the main methods. – Jim Garrison Jul 26 '16 at 05:13
  • @JimGarrison: the OP already mentioned that he has "[…] tested the code with 1 million elements". – beatngu13 Jul 26 '16 at 13:05
  • Not an answer but, your code would be cleaner if your `run()` method did not have to examine the thread name in order to decide which part of the array to process. Usually, if you want different threads to do different things, then you should give them different `Runnable` instances. In your case, I would make them different instances of the same class, and I would make `start` and `end` constructor arguments. – Solomon Slow Jul 26 '16 at 13:19

2 Answers2

1

You don't have to program this from scratch:

Arrays.parallelSetAll(arr, x -> x * x);

parallelSetAll creates a parallel stream which does all the work for you:

Set all elements of the specified array, in parallel, using the provided generator function to compute each element.

If you'd like to know how to control the number of threads used for parallel processing, checkout this question.

Community
  • 1
  • 1
beatngu13
  • 7,201
  • 6
  • 37
  • 66
  • @beatnu13, I did populate the elements in the array with random numbers but that method has no relevence with respect to the question at hand, so did not post it. Thanks for the snippet on parallel stream. Will look it up. – The Government Jul 26 '16 at 18:18
  • @TheGovernment: OK, didn't know that. I removed the comment. – beatngu13 Jul 27 '16 at 12:26
0

I recommend you add the following code to the end of your main method to ensure they each finish their work:

     try {
        doubleOne.join(); //Waits for this thread to die. 

        doubleTwo.join(); //Waits for this thread to die. 
     } catch (InterruptedException e) {
        e.printStackTrace();
    }

You are creating two threads that could be executed in parallel provided that the scheduler chooses to interleave them. However, the scheduler is not guaranteed to interleave the execution. Your code works in parallel on my system (...sometimes.. but other times, the threads execute in series).

Since you are not waiting for the threads to complete (using the join method), it is less likely that you would observe the interleaving (since you only observe part of the program's execution).

Austin
  • 8,018
  • 2
  • 31
  • 37