-1

I have a Java program which creates threads each one executing the same code (the same run()).

My main looks like:

    {
                // Create threads   
                GameOfLifeThread[][] threads = new GameOfLifeThread[vSplit][hSplit];        
                for(int i=0; i<vSplit; i++){
                    for(int j=0; j<hSplit; j++){
                        threads[i][j] = new GameOfLifeThread(initalField, ...);
                    }
                }       
                // Run threads      
                for(int i=0; i<vSplit; i++){
                    for(int j=0; j<hSplit; j++){

                    //    threads[i][j].run();
                          (new Thread(threads[i][j])).start();
                    }
                }   

                return ...;
    }

initialField is a global 2D array. Each thread is supposed to make some changes to it. The problem is that after the threads execution the array stays unchanged even if there is only a single worker thread. However, when I run

threads[i][j].run();

instead of

(new Thread(threads[i][j])).start();

with a single worker thread (i.e. pure serial execution by the main thread) the initalField changes as it should.

What could be the problem? It looks like the array's elements are passed by value, but it cannot be so.

Thank you in advance.

user3032925
  • 81
  • 1
  • 1
  • 6

1 Answers1

0

Just one guess in the blue:
Your initalField must be volatile, otherwise it may be cached by the threads and won't get changed (as viewed by the other threads), because they can get cached thread-locally.

This and this answer may explain it a bit better.

Community
  • 1
  • 1
Burkhard
  • 14,596
  • 22
  • 87
  • 108