title: How to parallelize this groovy code?
body: <p>I'm trying to write a reusable component in Groovy to easily shoot off emails from some of our Java applications.  I would like to pass it a List, where Email is just a POJO(POGO?) with some email info.  I'd like it to be multithreaded, at least running all the email logic in a second thread, or make one thread per email.  </p>
  
  <p>I am really foggy on multithreading in Java so that probably doesn't help!  I've attempted a few different ways, but here is what I have right now:</p>
  
  <pre><code>void sendEmails(List&lt;Email&gt; emails) {
  
      def threads = []
  
      def sendEm = emails.each{ email -&gt;
          def th = new Thread({
              Random rand = new Random()
              def wait = (long)(rand.nextDouble() * 1000)
              println "in closure"
              this.sleep wait
              sendEmail(email)
          })
          println "putting thread in list"
          threads &lt;&lt; th
      }
  
      threads.each { it.run() }
      threads.each { it.join() }
  
  }
  </code></pre>
  
  <p>I was hoping the sleep would randomly slow some threads down so the console output wouldn't be sequential.  Instead, I see this:</p>
  
  <pre><code>putting thread in list
  putting thread in list
  putting thread in list
  putting thread in list
  putting thread in list
  putting thread in list
  putting thread in list
  putting thread in list
  putting thread in list
  putting thread in list
  in closure
  sending email1
  in closure
  sending email2
  in closure
  sending email3
  in closure
  sending email4
  in closure
  sending email5
  in closure
  sending email6
  in closure
  sending email7
  in closure
  sending email8
  in closure
  sending email9
  in closure
  sending email10
  </code></pre>
  
  <p>sendEmail basically does what you'd expect, including the println statement, and the client that calls this follows,</p>
  
  <pre><code>void doSomething() {
  
      Mailman emailer = MailmanFactory.getExchangeEmailer()
  
      def to = ["one","two"]
      def from = "noreply"
  
      def li = []
      def email   
      (1..10).each {
          email = new Email(to,null,from,"email"+it,"hello")
          li &lt;&lt; email
      }
  
      emailer.sendEmails li
  }
  </code></pre>