title: How do I sort a list of records using multithreading in java?
body: <p>I'm teaching myself multithreading in java. My dummy example is that I have a large list of records (a 2D array) that I want sorted. The single threaded approach is to use loop through the list of records and sort. I want to multithread my program to sort my list with a fixed number threads, in this case 2. One thread will sort the first half of the list and the second thread will sort the remaining half. Then I want to output the results, of the now sorted list of records.</p>
  
  <p>How can I create a thread pool of workers and sort the list of records? Do I need to worry about <code>data</code> being a shared resource? How do I return the results from each thread back to the original list of records? Below is my code.</p>
  
  <pre><code>import java.util.*;
  
  class RunnableProcess implements Runnable {
    private int[] data;
  
    public RunnableProcess(int[] data) {
        this.data = data;
    }
  
    public void run() {
      try {
  
        // sort the records this thread has access to
        for (int i = 0; i &lt; data.length; i++) {
          Arrays.sort(data[i]);
        }
  
      } catch(Exception ex) {
          ex.printStackTrace();
      }
    }
  }
  
  class BigData {
  
    static int[][] data = new int[1000][1000];
  
    public static void main(String [] args) {
  
  
      // Create records 
      for (int i = 0; i &lt; data.length; i++) {
        for (int j = 0; j &lt; data[0].length; j++) {
          data[i][j] = new Random().nextInt(999);
        }
      }
  
      // Call on two threads to sort the data variable
      // ExecutorService executor = Executors.newFixedThreadPool(2);
  
  
     // Python type of idea: Pass half the records to each thread and start
     // java doesn't support this so what is the java way of doing this?
  
     // Thread thread = new Thread(new RunnableProcess(data[:499]));
     // thread.start();
  
     // Thread thread = new Thread(new RunnableProcess(data[499:]));
     // thread.start();
  
    }
  }
  </code></pre>
  
  <p>I am open suggestions on the best way to tackle this problem.</p>