title: How can I combine the results of multiple threads?
body: <p>I am trying to perform a <code>replace</code> operation on the same string with multiple threads. I have created a class that will do so, given the text and a list of string arrays containing the targets and replacements:</p>
  
  <pre><code>public class ParallelReplacer implements Runnable {
      private String text = "";
      private List&lt;String[]&gt; targetsAndReplacements = null;
  
      public ParallelReplacer(String text, List&lt;String[]&gt; targetsAndReplacements) {
          this.text = text;
          this.targetsAndReplacements = targetsAndReplacements;
          run();
      }
  
      public void run() {
          for(String[] s : this.targetsAndReplacements) {
              this.text = performReplace(text, s);
          }
      }
  
      private String performReplace(String text, String[] targetAndReplacement) {
          text = text.replace(targetAndReplacement[0], targetAndReplacement[1]);
          return text;
      }
  }
  </code></pre>
  
  <p>I execute it like so:</p>
  
  <pre><code>List&lt;String[]&gt; targetsAndReplacements = new ArrayList&lt;String[]&gt;();
  targetsAndReplacements.add(new String[] {"a", ""});
  targetsAndReplacements.add(new String[] {"e", ""});
  targetsAndReplacements.add(new String[] {"i", ""});
  targetsAndReplacements.add(new String[] {"o", ""});
  targetsAndReplacements.add(new String[] {"u", ""});
  
  String text = "I am trying to perform a replace operation the same string with multiple threads.";
  text = new ParallelReplacer(text, targetsAndReplacements.subList(0, targetsAndReplacements.size() / 2)).getResults();
  text = new ParallelReplacer(text, targetsAndReplacements.subList(targetsAndReplacements.size() / 2, targetsAndReplacements.size())).getResults();
  </code></pre>
  
  <p>However, the second thread only executes after the first thread has finished, defeating the purpose of haveing multiple threads. How can I have the two threads executing simultaneously, and then merge the results after they are done?</p>